You can invert the sorting of any range by using a greater-than comparison instead of the default less-than:
std::sort(values.begin(), values.end(), std::greater<std::pair<string, int>>());
Alternatively, you can reverse the order of iteration:
std::sort(values.rbegin(), values.rend());
Edit If you want to change the comparison criteria to compare lexicographically by the pair's second
first and it's first
next, you can provide your own comparison function. It must still satisfy strict weak ordering as in the examples above. Lexicographical comparisons are trivial to implement with std::tie
:
#include <tuple>
template<typename T1, typename T2>
struct pair_backwards_greater
{
bool operator()(const std::pair<T1, T2>& lhs, const std::pair<T1, T2>& rhs) const
{
return std::tie(lhs.second, lhs.first) > std::tie(rhs.second, rhs.first);
}
};
then
std::sort(values.begin(), values.end(), pair_backwards_greater<string, int>());
You also have the option of using a simple lambda expression instead of writing the functor by hand:
std::sort(values.begin(), values.end(),
[](const std::pair<std::string, int> &lhs, const std::pair<std::string, int> &rhs)
{
return std::tie(lhs.second, lhs.first) > std::tie(rhs.second, rhs.first);
}
);
std::tie
requires C++11 library support, but there are C++03 alternative implementations in boost::tie
and std::tr1::tie
. Lambda expressions require C++11 language support.