Reputation: 18137
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;
}
Upvotes: 23
Views: 27485
Reputation: 311
From what I understand you want to know why the code compiles with A*
even if you dont have the operator<
and how to change the order from ascending to descending.
It compiles because it is using the operator<
with the pointers address.
change cout << (*itr)->x << endl;
to cout << (*itr)->x << ' ' << *itr << endl;
and you'll see it easily :)
It is normal that the code doesn't compile without the operator<
if you're using the set<A>
. It won't know what to compare in order to insert the members sorted. So you have to provide that operator!
If you want to keep using pointers, you can use the code provided by @juanchopanza.
Upvotes: 0
Reputation: 227418
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:
struct APtrComp
{
bool operator()(const A* lhs, const A* rhs) const { /* implement logic here */ }
};
And instantiate your set using it as second template parameter.
set<A*, APtrComp> numbers;
Upvotes: 32
Reputation: 20084
If you remember your pointer arithmetic, all points are given a set of operators to use in operations(which includes the operator<). Your set will use this default operator < .
Upvotes: 1
Reputation: 19443
you have a set of pointers. usually pointers are allocated in increasing order. and pointers have a default <
operator. so this is why it's compiling and working.
P.s. it will print you the value of A1 A2 A3 in this order no matter what's there values:
...
A* a1 = new A(9);
A* a2 = new A(5);
A* a3 = new A(1);
...
// output: 9 5 1
Upvotes: 3