hell_hacker's blog

By hell_hacker, history, 8 days ago, In English,

I had a vector of pairs. I wanted it sorted in descending according to the first value of the vector.

sort(a.begin(),a.end(),[](pair<int,int> &left, pair<int,int> &right){
         return left.first >= right.first;
});

This gave me TLE. Sorting it normally

sort(a.begin(),a.end());

and iterating from the end worked.

Why does the first sorting function give TLE? Do I have to implement it some other way?

 
 
 
 
  • Vote: I like it  
  • +4
  • Vote: I do not like it  

»
8 days ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by hell_hacker (previous revision, new revision, compare).

»
8 days ago, # |
  Vote: I like it +1 Vote: I do not like it

sort requires its comparison operator to be strict.

This code should work:

sort(a.begin(),a.end(),[](pair<int,int> &left, pair<int,int> &right){
         return left.first > right.first;
});
»
8 days ago, # |
  Vote: I like it +5 Vote: I do not like it

There's no need to write custom comparator inline, because comparators for pair<int,int> are already there. You can simply write sort(a.begin(), a.end(), greater<pair<int,int>>());.

»
7 days ago, # |
  Vote: I like it 0 Vote: I do not like it

why not sort(a.rbegin(),a.rend())?