1

在 C++03 中,我想创建一个 std::set 迭代时,一个整数首先出现,之后,我不在乎什么顺序,但我需要一个顺序来确保没有重复放。例如,如果我有一组年份,并且在迭代时我希望在所有其他年份之前处理 2010 年。

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);
}

基本上,我需要提供一个比较器,在运行时已知的某个年份(例如 2010 年)与所有其他年份相比要少,但剩余年份是有序的,但没有任何必要的顺序,只是为了确保没有重复放。

4

2 回答 2

6
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;
    }
};

要基于以下命令创建std::set该订单的实例Comparer

std::set<int, Comparer> instance( Comparer(2010) );
于 2013-04-25T17:10:50.650 回答
0
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));
于 2013-04-25T17:12:10.960 回答