Wil*_*mKF 1 c++ comparator stdset c++03
在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);
}
Run Code Online (Sandbox Code Playgroud)
基本上,我需要提供一个比较器,在运行时已知的某一年(例如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;
}
};
Run Code Online (Sandbox Code Playgroud)
要根据以下内容创建std::set该订单的实例Comparer:
std::set<int, Comparer> instance( Comparer(2010) );
Run Code Online (Sandbox Code Playgroud)