Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of elements in set of pointers

Tags:

c++

set

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;
}
like image 882
B Faley Avatar asked Nov 05 '12 14:11

B Faley


People also ask

Are sets ordered C++?

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.

What are pointers for C++?

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.

What does* mean in pointers?

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.


Video Answer


1 Answers

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;
like image 192
juanchopanza Avatar answered Sep 17 '22 11:09

juanchopanza