-1

I have a vector of pair I want to sort. I want to sort by first element in ascending order, and if the first element is equal, I want to sort it by descending order of the second element.

Example:

3 2
1 9 
0 4
3 3

When sorted, it has to be:

0 4
1 9
3 3
3 2

Is there any way I could achieve this in c++?

mhmd
  • 11
  • 1

1 Answers1

2

Like the guys in comments said, std::sort should work fine with some lambda. Something like this I guess:

std::vector<std::pair<int, int>> vec{
    {3, 2},
    {1, 9},
    {0, 4},
    {3, 3}
};

std::sort(vec.begin(), vec.end(), [](const auto& l, const auto& r){
    return (l.first == r.first) ? l.second > r.second : l.first < r.first;   
});
Hekmatyar
  • 335
  • 2
  • 10