如何在c++中创建一组非标准顺序的整数

How to create set of integers with non-standard order in C++?

本文关键字:一组 非标准 顺序 整数 c++ 创建      更新时间:2023-10-16

在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年)比所有其他年份比较少,但其余年份排序,但不是按照任何必要的顺序,只是排序以确保集合中没有重复。

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

创建一个基于Comparer排序的std::set实例:

std::set<int, Comparer> instance( Comparer(2010) );
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));