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;
}
What is Set in C++? As mentioned above, sets in C++ are the type of STL containers that are used for storing elements in a sorted way. The operations allowed to be performed on sets are insertion and deletion. The elements are internally sorted according to a strict weak ordering in a set type container.
Pointers (C++) A pointer is a variable that stores the memory address of an object. Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.
It means that a pointer variable my_pointer is pointing (it is containing the address of) to my_variable. If my_variable is an integer, then, when you declare your pointer, it must also be an integer pointer.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With