How do I sort a vector of pairs by both of the values rather than just the second one? [duplicate]
The simplest way is to use the standard functions std::sort()
and std::tie()
.
Here is a demonstration program:
#include <iostream>
#include <utility>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<std::pair<int, double>> v =
{
{ 2, 2.4 },
{ 9, 3.0 },
{ 10, 3.1 },
{ 1, 2.4 },
{ 5, 3.1 }
};
std::sort( std::begin( v ), std::end( v ),
[]( const auto &p1, const auto &p2 )
{
return std::tie( p2.second, p1.first ) < std::tie( p1.second, p2.first );
} );
for (const auto &p : v)
{
std::cout << p.first << ' ' << p.second << '\n';
}
}
The program output is:
5 3.1
10 3.1
9 3
1 2.4
2 2.4