How does one go about sorting a vector containing custom (i.e. user defined) objects.
Probably, standard STL algorithm sort along with a predicate (a fu
You are on the right track. std::sort
will use operator<
as comparison function by default. So in order to sort your objects, you will either have to overload bool operator<( const T&, const T& )
or provide a functor that does the comparison, much like this:
struct C {
int i;
static bool before( const C& c1, const C& c2 ) { return c1.i < c2.i; }
};
bool operator<( const C& c1, const C& c2 ) { return c1.i > c2.i; }
std::vector values;
std::sort( values.begin(), values.end() ); // uses operator<
std::sort( values.begin(), values.end(), C::before );
The advantage of the usage of a functor is that you can use a function with access to the class' private members.