Domanda

In C++03, I'd like to create a std::set where when iterating, one integer comes first, after that, I don't care what order, but I need an ordering to ensure there are no duplicates in the set. For example, if I had a set of years, and when iterating I want 2010 to be processed before all other years.

std::set<int> years;

// I do not know the set of years up front, so cannot just make a vector, plus
// there could potentially be duplicates of the same year inserted more than
// once, but it should only appear once in the resultant set.
years.insert(2000);
years.insert(2001);
years.insert(2010);
years.insert(2011);
years.insert(2013);

for (std::set<int>::iterator itr = years.begin(); itr != years.end(); ++itr) {
   process_year(*itr);
}

Basically, I need to provide a comparator for which some year, known at runtime, (e.g. 2010) compares less than all other years, but the remaining years are ordered, but not in any necessary order, just ordered to ensure no duplicates in the set.

È stato utile?

Soluzione

struct Comparer
{
    int val;
    Comparer(int v):val(v) {}
    bool operator()(int lhs, int rhs) const {
        if (rhs == val) return false;
        if (lhs == val) return true;
        return lhs < rhs;
    }
};

To create an instance of the std::set that orders based on Comparer:

std::set<int, Comparer> instance( Comparer(2010) );

Altri suggerimenti

struct my_compare {
    my_compare(int y) : allw_less(y) {}
    bool operator() (const int& lhs, const int& rhs) const{
        if(rhs == allw_less)
           return false;
        if(lhs == allw_less)
           return true;
        else
            return lhs < rhs;
    }
private:
    int allw_less; 
};


typedef std::set<int, my_compare> setType;
setType years(my_compare(2010));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top