简体   繁体   中英

Sorting a std::vector with elements of type pair<int, string>, but in reverse order

I am trying to sort a std::vector containing elements of type pair <int, string> in decreasing order.

I was trying to accomplish this by using sort(Datas.begin(), Datas.end()) , but the end result is a vector sorted in ascending order. I also tried using sort(Datas.begin(), Datas.end(), greater<int>) , but this resulted in a compilation error.

For clarity, here is my code:

#include <utility>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <functional>
#include <array>
using namespace std;

int main()
{
    vector<pair<int, string>> Datas;
    Datas.emplace_back(4, "bbbbbbbbb");
    Datas.emplace_back(2, "yyytyuytuyt");
    Datas.emplace_back(20, "asdadxxsadas");
    Datas.emplace_back(1, "ccccccccc");

    sort(Datas.begin(), Datas.end());


    for (const auto& e : Datas)
        {
            cout << e.second << " " << e.first <<'\n';
        }
    cout << '\n';

}

Can somebody explain why the error occurs, and also explain how to sort a std::vector in decreasing order?

You can use the following syntax:

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

This syntax ensures that the list will be sorted in reverse order. You can also sort the list normally, then use std::reverse .

Your approach where you use greater<int> would successfully sort the list in reverse order if all the elements were of type int , but your code results in an error because you are passing elements of type pair<int, string> to greater<int> , which is not allowed.

Alternative to Telescope's answer, if you want to use std::greater , you have to specify the correct type. In your case, it would be:

sort(Datas.begin(), Datas.end(), std::greater<std::pair<int,string>>());

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