简体   繁体   中英

C++ - Sorting first and second of a vector of pair at the same time

vector<pair<int, char>> pair_vec;

I have such a vector containing pairs. I'd like to sort second of pair in descending order, and if there are two pairs with the same value of char , those two should be then sorted by first of pair of ascending order.

sort(pair_vec.begin(), pair_vec.end(), sortbysecdesc);

This is the code I used to sort the vector. But it can only sort it solely based on second of pair.

bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
       return a.second > b.second;
}

This is the driver function I used. How do I code to sort the vector by first in ascending order if a few seconds are the same

Use this-

bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
       if(a.second==b.second)
            return a.first<b.first;
       return a.second > b.second;
}

You need to check if the second values compare equal, and if so then return the result of comparing the first values instead, otherwise return the result of comparing the second values:

bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
    return (a.second == b.second) ? (a.first < b.first) : (a.second > b.second);
}

For example:

vector<pair<int, char>> pair_vec{ {1,'a'}, {2,'b'}, {3,'b'}, {4,'b'}, {5,'f'}, };
sort(pair_vec.begin(), pair_vec.end(), sortbysecdesc);
for (auto &p : pair_vec)
    cout << p.first << ' ' << p.second << endl;

Output:

5 f
2 b
3 b
4 b
1 a

Live Demo

Change your binary function to

bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
    return (a.second == b.second) ? a.first < b.first : a.second > b.second;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM