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.
Author by
Amit Kumar
Updated on June 07, 2022Comments
-
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 over 10 yearsIt might be worth mentioning that the compare function you supply to
sort
must returnbool
, not the larger element. -
juanchopanza over 10 years@AlexReinking Correct, I was in the process of adding that.
-
Amit Kumar over 10 yearsit is throwing an error. In function 'int main()':| error: '>>' should be '> >' within a nested template argument list|
-
juanchopanza over 10 years@AmitKumar You can replace
>>
by> >
, or compile in C++11 mode. I was assuming a C++11 compiler.