Foreword
Since the original question turned out to be a misunderstanding, and the code in it is already the correct answer, I decided to write and publish a little about using std::sort in general.
std::sort sorts the range in ascending order, determined by the weak ordering of the elements. By default, it uses the < operator defined on elements, but it can also take a function object or functor to provide a comparison. This functor must have a properly overloaded function with the signature bool operator()(const T& lhs, const T& rhs) const . An example of this follows:
struct FooSorter { bool operator (const Foo& lhs, const Foo& rhs) const { return lhs.ham_index < rhs.ham_index; } }; std::sort(begin(vec), end(vec), FooSorter());
This would sort the full range represented by vec according to the criteria defined in the FooSorter operator() .
Since writing user-defined functions for simple things (sorting in decreasing order, sorting in increasing order) will quickly become painful, STL provides many template functors ready for use in functional . The following values โโare important for sorting:
std::equal_to implementation x == y
std::not_equal_to implementation x! = y
std::greater implementation x> y
std::less implementation x <y
std::greater_equal implementation x> = y
std::less_equal implementation x <= y
They are all templates and can be used for any type that implements the necessary operators. Using them is easy:
std::sort(begin(vec), end(vec), std::greater<int>());
This sorts the range represented by the vector in descending order.
But, since one of the biggest problems with STL algorithms was the pain of defining functors, C ++ 11 brings a new trick: lambda functions . This allows you to declare a functional object equivalent to a built-in one. Example:
std::sort(begin(vec), end(vec), [](int lhs, int rhs){return rhs > lhs});
It also sorts the range represented by the vector in descending order, but we donโt need to explicitly declare a functor (or use an already declared functor). (This gets much better when implementing much more complex comparisons or functors for different STL algorithms.)