Domanda

How to sort a vector of pairs in descending order when the pair is incr<int,int>using the std::sort() in STL?It should sort first with respect to the first element and then the second.

È stato utile?

Soluzione

The operator< is overloaded for pair<int,int> so you can sort a vector of pairs just like any other vector. If you need descending order, you have two options - either sort and then call std::reverse to reverse the result or provide predicate for the sorting.

You can also make use of std::greater:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<pair<int, int> > a;
    a.push_back(make_pair(1, 2));
    a.push_back(make_pair(2, 3));
    sort(a.begin(), a.end(), greater<pair<int,int> >());
    return 0;
}

Altri suggerimenti

use this,

template<class T>
struct sortFunctor: public unary_function<std::pair<int, int>, std::pair<int, int>>
{
    bool operator()(const std::pair<int, int>& First, const std::pair<int, int>& Second)
    {
        if(First.first < Second.first)
        {
            return false;
        }
        if(First.first == Second.first && First.second < Second.second)
        {
            return false;
        }
        return true;
    }
}

then pass this functor as a third parameter to sort function.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top