Alejandro Silvestri
Alejandro Silvestri

Reputation: 3784

std::set<myClass*> sorted

I wonder how is the most convenient way to have a sorted set, a set of pointers to objects, like

std::set<myClass*> mySet;

I want this set to be sorted by myClass::someProperty (say, an int).

Should I overload operator < in myClass? I'm not sure if it will work, because it's not a set of myClass, but a set of pointers.

How can I define a compare function?

Thank you very much.

Upvotes: 0

Views: 85

Answers (2)

PapaDiHatti
PapaDiHatti

Reputation: 1921

You can also specialize std::less for your myClass* as given below and then no need to pass comparator while creating set:

namespace std {
template<>
struct less<myClass*>
{
   bool operator()(const myClass* k1, const myClass* k2) const
   {
      // Some code ...
   }
};
}

Upvotes: 3

Jerry Coffin
Jerry Coffin

Reputation: 490768

You need to define a type (or a function) that dereferences the pointers and compares the attributes of the objects they point at, something on this general order:

class myClass {
    int value;
public:
    myClass(int i = 0) : value(i) {}

    struct cmp {
        bool operator()(myClass *const &a, myClass *const &b) const {
            return a->value < b->value;
        }
    };
};

We they define the set something like this:

std::set<myClass*, myClass::cmp> mySet;

My advice, however, would be to store objects instead of pointers (if possible).

Upvotes: 4

Related Questions