C++ – Sort a std::list with theclass::operator<(theclass &other)

cstd

I have a std::list<myclass*> and in my class I have myclass::operator<(myclass &other) defined.

I use the std::list.sort() function, but it does not change anything in that list. Maybe it just sorts the pointers?

How can I sort the actual items in that list?

Best Answer

You are sorting the pointer values, not the myclass values. You have to write your own predicate to compare pointers by dereference:

template <typename T> bool PComp(const T * const & a, const T * const & b)
{
   return *a < *b;
}

std::vector<Foo*> myvec;
std::list<Foo*> mylist;
std::sort(myvec.begin(), myvec.end(), PComp<Foo>);
mylist.sort(PComp<Foo>);

By the way, I think you cannot sort std::list with std::sort from <algorithm> because it is not random access. Use the member function sort instead as MerickOWA says. (But that's generally less efficient than sorting a random-access container.) Alternatively, you can immediately store your objects in a sorted container like std::set<Foo*, PPred>, where PPred is the functor version of the predicate:

struct PPred {
  template <typename T> inline bool operator()(const T * a, const T * b) const
  { return *a < *b; }
};