I wrote the following functor, with the expectation that all the elements in the set will be added in reverse order of their insertion:
struct cmp {
bool operator () (int a, int b) {
return false;
}
};
and when I tested it as below, the only value added to the set is 1.
int main() {
set<int, cmp > combos;
combos.insert(1);
combos.insert(4);
combos.insert(7);
combos.insert(5);
combos.insert(9);
combos.insert(1);
for (int a : combos) {
cout << a << endl;
}
return 0;
}
However, when I changed the functor to return true each time, all the values get added to the set in the order they were inserted [1, 4, 7, 5, 9, 1]
. I thought that when the functor comparator returns true
, it is treated as if the first element is smaller than the second element, and false means that the first element is treated as grater than the second element? It seems to be the case when I did return (a < b);
and return (a > b);
in the operator function.
In this case, std::set
uses !(a < b) && !(b < a)
to determine equality of two elements: a
and b
.
!(false) && !(false)
will be yielding true
everytime, when checking for duplicates, thus not allowing std::set
to contain more than one element. This is a mistreatment of std::set
.