What I am looking to do is sort a vector of pairs in a way where the first value is lowest to greatest and the second being greatest to lowest and having priority over the first value ordering whilst keeping them together. For example, let's say I had this code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
pair<int, double> p;
vector<pair<int, double> > vp;
p.first = 2;
p.second = 2.4;
vp.push_back(p);
p.first = 9;
p.second = 3.0;
vp.push_back(p);
p.first = 10;
p.second = 3.1;
vp.push_back(p);
p.first = 1;
p.second = 2.4;
vp.push_back(p);
p.first = 5;
p.second = 3.1;
vp.push_back(p);
}
if I were to print it out via loop I'd want it to go from outputting this:
2, 2.4
9, 3.0
10, 3.1
1, 2.4
5, 3.1
to outputting this
5, 3.1
10, 3.1
9, 3.0
1, 2.4
2, 2.4
Now imagine if those values weren't given manually but instead they were random and being randomized over a for loop that loops a random amount of times from between 0 and 100 inclusive each time the code is run, each new random value of both sides of the pair being stored in the vector (which would give the vector a size of 10.)
How do I sort out the vector so it would have output that is ordered the same as the above example?
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