Why does the following code get compiled even though I have commented the A::operator<. I wonder how the output of the following code is printed in ascending order without the < operator. How can I change the order to descending? (note: this code does not get compiled if I use A instead of A* unless I provide a definition for A::operator<)
#include <iostream>
#include <set>
using namespace std;
class A
{
public:
A(int v):x(v){}
virtual ~A(){}
int x;
/*bool operator<(const A &a) const
{
return x > a.x;
}*/
};
int main()
{
set<A*> numbers;
A* a1 = new A(1);
A* a2 = new A(2);
A* a3 = new A(3);
numbers.insert(a2);
numbers.insert(a3);
numbers.insert(a1);
for(set<A*>::iterator itr = numbers.begin();itr!=numbers.end();itr++)
{
cout << (*itr)->x << endl;
}
// output: 1 2 3
return 0;
}
Your code gets compiled because you have a set of pointers. Since the set contains pointers, and your operator does not compare pointers, but rather, objects of type
A, it is not needed for the set. There is an existing pointer less-than comparison operator, which is what gets used in your set.You can change the ordering by providing your own comparator implementing strict weak ordering:
And instantiate your set using it as second template parameter.