How can I sort a vector containing pair<int,int> elements? Sorting is done as per the compare function

10,582

Presumably you want to sort them lexicographically, in increasing order. You can do this:

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

The comparison functor is a binary predicate, and must return a boolean, and implement strict weak ordering. std::greater<std::pair<int,int>> does that for you.

Share:
10,582
Amit Kumar
Author by

Amit Kumar

Updated on June 07, 2022

Comments

  • Amit Kumar
    Amit Kumar almost 2 years
    typedef pair<int,int>ii;
    vector<ii>vii;
    
    sort(vii.begin(),vii.end(),comp);
    
     ii comp(ii a,ii b){
       if(a.first>b.first)
       return a;
       else if(a.first==b.first){
        if(a.second>b.second)
        return a;
        else
        return b;
       }
       else{
        return b;
       }
     }
    

    //This way it is throwing a compilation error. Can you guide how to sort this vector as per //the conditions given in the compare function.

  • Alex Reinking
    Alex Reinking over 10 years
    It might be worth mentioning that the compare function you supply to sort must return bool, not the larger element.
  • juanchopanza
    juanchopanza over 10 years
    @AlexReinking Correct, I was in the process of adding that.
  • Amit Kumar
    Amit Kumar over 10 years
    it is throwing an error. In function 'int main()':| error: '>>' should be '> >' within a nested template argument list|
  • juanchopanza
    juanchopanza over 10 years
    @AmitKumar You can replace >> by > >, or compile in C++11 mode. I was assuming a C++11 compiler.