【发布时间】:2013-01-13 00:54:28
【问题描述】:
我试图运行以下代码。我发现输出存在差异。我了解比较器功能中使用的排序机制存在问题。我基本上在寻找的是: 1)Set如何在内部存储数据。 2)如何解决此问题或将数据复制到不同集合的最佳方法。 3) 排序究竟是如何造成这个问题的。
#include <iostream>
#include <set>
using namespace std;
struct Comparator {
bool operator()( const int& a, const int& b ) {
if( a <= b )
return true;
else
return false;
}
};
int main()
{
set< int, Comparator > customSet;
for( unsigned k = 0, index = 2; k < 10; ++k ) {
customSet.insert( index );
}
set< int, Comparator >::iterator iter = customSet.begin();
for(; iter != customSet.end(); ++iter ) {
cout<<*iter<<endl;
}
cout<<"---------------------------------"<<endl;
set< int, Comparator > tempCustomSet ;//= customSet;
tempCustomSet.insert( customSet.begin(), customSet.end() );
iter = tempCustomSet.begin();
for(; iter != tempCustomSet.end(); ++iter ) {
cout<<*iter<<endl;
}
return 0;
}
【问题讨论】:
-
您的情况不安全。应该说,
if ((a <= b) == true ? true : false) { return a <= b ? true : false } else return {!true && false; }。一个常见的错误。
标签: c++ stl set equivalence strict-weak-ordering