User defined Comparator

// What will be the output of the following C++ code?

#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;
struct Compare
{
bool operator()(pi const &a, pi const &b)
{
if (a.second < b.second)
{
return true;
}
else if (a.second > b.second)
{
return false;
}
else
{
if (a.first > b.first)
{
return true;
}
return false;
}
}
};
int main()
{
priority_queue<pi, vector, Compare> q;
q.push({1, 5});
q.push({5, 15});
q.push({7, 15});
q.push({10, 2});
q.push({1, 10});
cout << q.top().first << " " << q.top().second << endl;
return 0;
}

I am unable to understand how the comparator worked . kindly help.

Your code works now https://ide.codingblocks.com/s/643402
In priority queue comparator works in reverse logic.
First elements are sorted in descending order on basis of 2nd element. Then if there is a tie among them then elements are sorted in ascending order on basis of first element here.

In the compare class, it returns true when a.second < b.second which implies the sequence should have been sorted in ascending order(according to SECOND value), and when there is a tie, pair with larger FIRST value will be there in the sequence before the other . The sequence then should have been ->
({10,2},{1,5},{1,10},{7,15},{5,15}).
The top should be pointing to {10,2}.
Is it so or the other way around? if i am getting it wrong please suggest me some resource as i get so much confused in user defined comparators i.e. when to arrange in ascending and when to arrange descending.

Like I said priority works in opposite way. So if you make comparator as ascending it gives descending. See the articles on it, it will become clearer.

1 Like

Okay , your last line made things clear.
Thank you .

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.