0

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.

Alejandro Silvestri
  • 3,706
  • 31
  • 43

2 Answers2

4

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).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
3

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 ...
   }
};
}
PapaDiHatti
  • 1,841
  • 19
  • 26