Custom Compare Function for Sorting in C++ STL

Revision en1, by adipro1167, 2020-06-08 13:47:24

Hello Codeforces! In the contest, Codeforces Round #648, in B problem- Trouble Sort, I thought of using the Custom Compare Function, though later I realized it wasn't required here. But a general problem that I have faced in Custom Compare Function is that I have never understood its working. Sometimes, I make my own Custom Functions and they work but how- I don't understand. I read about it on Sort()-CPP Reference and Sort(): GeeksForGeeks but I did not understand its working. I wrote the following code:

#define lpr pair<long long int,long long int>
#define S second
#define F first
#define ll long long int
bool comparefn(lpr a, lpr b)
{
    if(a.S!=b.S)
    return a.F<=b.F;
    return false;
}

This is my custom compare function and I used it as:

vector<lpr> a;
sort(a.begin(),a.end(),comparefn)

It passed the first test case successfully but failed in the second one. On debugging I found that it fails for the following case:

5 1 5
0 0 1

Output: No But for the case:

5 5 1
0 1 0

Output: Yes. It works correctly.

Please explain me a dry run of this test case with the custom compare function which I have made. It would be of great help. Thanks in Advance!

Tags #sorting, sortings, custom comparator, sort()

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English adipro1167 2020-06-08 13:47:24 1505 Initial revision (published)