Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 361
Amit Kumar Avatar asked Feb 14 '23 18:02

Amit Kumar


1 Answers

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.

like image 152
juanchopanza Avatar answered Apr 28 '23 19:04

juanchopanza