babidi
babidi

Reputation: 19

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?

Upvotes: 0

Views: 82

Answers (2)

ChrisMM
ChrisMM

Reputation: 10057

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>>());

Upvotes: 4

Christopher Miller
Christopher Miller

Reputation: 3461

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.

Upvotes: 4

Related Questions