如何在c++中创建一组非标准顺序的整数
How to create set of integers with non-standard order in C++?
在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));
相关文章:
- 在 c++ 中拥有一组结构的正确方法是什么?
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- C4204:使用的非标准扩展:非常量聚合初始值设定项
- 一组值的零开销下标运算符
- 效率:标准::数组与标准::矢量
- 使用一组结构,避免在一组结构中出现重复的结构
- CMake:我们可以为一组不形成可执行文件或库的特定文件指定包含目录吗?
- 合并一组模板专用化
- 如何更好地检查两个 char 变量是否在一组值中?
- 使用标准库或Boost库从一组数据中计算直方图
- 将 constexpr 数组扩展为一组非类型模板参数
- 是否有一种替换C风格的Bool数组的标准方法
- 如何在不与标准库运算符冲突的情况下为一组相关类重载运算符?
- MySQL 使用一组列中的数据更新列,以非零值为准
- 如何在c++中使用两个排序标准(对于一组对)创建有序集
- 用C++编写一组标准的算法
- 是否有一组标准编译器选项
- 如何在c++中创建一组非标准顺序的整数
- C++保留了一组指向模板对象的指针,这些指针都派生自一个非模板类