0

This is the output of my sorted vector of pair<int, char>:

6 X
6 E
6 C
5 D
4 D
4 B
2 A

But I want it to be sorted by the integer in descending order and alphabetically ascending where the integer is the same. Like this:

6 C
6 E
6 X
5 D
4 D
4 B
2 A

Here is my code:

#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<pair<int, char>> v;
    v.push_back(make_pair(5, 'D'));
    v.push_back(make_pair(2, 'A'));
    v.push_back(make_pair(6, 'C'));
    v.push_back(make_pair(4, 'B'));
    v.push_back(make_pair(4, 'D'));
    v.push_back(make_pair(6, 'X'));
    v.push_back(make_pair(6, 'E'));

    sort(v.rbegin(), v.rend());

    for (auto x: v)
        cout << x.first << " " << x.second << endl;

    return 0;
}

1 Answers1

0

You can write it manually:

sort(v.begin(), v.end(),
  [](auto a, auto b) {
    return a.first > b.first || (a.first == b.first && a.second < b.second);
  }
);
David G
  • 94,763
  • 41
  • 167
  • 253