How do i sort pair like this for example :
Input :
1 99
2 100
1 100
3 400
2 101
output :
1 100
1 99
2 101
2 100
3 400
How do i sort pair like this for example :
Input :
1 99
2 100
1 100
3 400
2 101
output :
1 100
1 99
2 101
2 100
3 400
Create a comparator and use the std::sort
function.
struct Comp {
bool operator()(const std::pair<int, int> &a, const std::pair<int, int> &b) {
if (a.first != b.first) {
return a.first < b.first;
}
return a.second > b.second;
}
};
Then create an instance of the struct and pass it into std::sort
.
Comp comp_functor;
std::sort(myVec.begin(), myVec.end(), comp_functor);
To do this you'd need to #include <algorithm>
. Also note that std::sort
does not guarantee stability so if you want stability use std::stable_sort
.