I was trying to run the below code. What I am finding is that there is difference in the output. I understand that there is an issue with ordering mechanism used in the Comparator functionality. What I am basically looking for is: 1) How does Set internally stores data. 2) How can I resolve this issue or the best way to copy the data to a different Set. 3) How exactly the ordering is creating this issue.
#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;
}
See this reference for more details on
std::set. The implementation should not concern you (they can differ from platform to platform), since the interface and complexity guarantees is all that matters to the Standard. Typical implementations are using red-black-trees.You need to make your
Comparatoruseoperator<and notoperator<=. The reason is thatstd::setwill consider elements equivalent if!Comparator(a, b) && !Comparator(b, a)evaluates totrue(i.e. neither is strictly less than the other).But with
<=, you havea <= aequal totrue, so that!(a<=a) && !(a<=a)givesfalsefor equal elements. Whereas with<you havea < aequal tofalseso!(a<a) && !(a<a)givestrue.The right to thing to do is:
This will guarantee that equal elements are considered equivalent. Note that this is discussed at length in Effective STL, "Item 19. Understand the difference between equality and equivalence."