【问题标题】:How to create set of integers with non-standard order in C++?如何在 C++ 中创建具有非标准顺序的整数集?
【发布时间】:2013-04-25 17:07:00
【问题描述】:

在 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 年)与所有其他年份相比,比较少,但剩余年份是有序的,但没有任何必要的顺序,只是为了确保没有集合中的重复项。

【问题讨论】:

  • “但我需要订购以确保集合中没有重复项”。嗯,不,你没有。

标签: c++ comparator c++03 stdset


【解决方案1】:
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) );

【讨论】:

  • 您没有展示如何实际使用比较器(例如,将其传递给集合)。
  • @Excelcius:OP 没有要求这样做。他要了比较器。
  • 你说的很对,但如果他们以前从未使用过比较器,这将有助于其他人更好地理解解决方案。在这个线程中的任何地方都没有提到它。
【解决方案2】:
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));

【讨论】:

  • 在这个方案中,比较值(2010)不能在运行时设置。
  • @Excelcius 他说在编译时就知道了。反正修好了。
  • lhsrhs 等于allw_less 时,这将返回true。它不应该。原因如下:ideone.com/4JmC83
  • @BenjaminLindley 该死! :)。应该多测试。无论如何,谢谢。
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 2020-01-01
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
相关资源
最近更新 更多