Sorting a vector of objects by a property of the object

Use std::sort and a functor. e.g:

struct SortByX
{
   bool operator() const (MyClass const & L, MyClass const & R) { return L.x < R.x; }
};

std::sort(vec.begin(), vec.end(), SortByX());

The functor’s operator() should return true if L is less than R for the sort order you desire.

Leave a Comment