I am not getting how to use Custom Comparator in priority_queue,
I am using :-
struct Comp
{
bool operator()( pair<string,int> a, pair<string,int> b)
{
if(a.second==b.second)
return a.first>b.first;
return a.second<b.second;
}
};
But reversing this is giving correct answer ,I think I have not understood logic .Help!!
Top K Frequent Word Leetcode
Hey @Bhawna
comparator in priority queue judges the element in opposite way as in sort function
what i mean is in priority queue Compare(a,b) tells us whether in the priority queue a will come before b or after b if
Compare(a,b) return true means a will come after b (b before a) and in case of false a will come before b
in this code you can judge that if a.second is less than b.second then a will come before b or if a.second is greater than b.second then b will come before a in case of equality in b.second we will check for a.first and b.first in that case if a.first is greater than b.first then a will come before b
so you can say that in priority queue the elements are stored in desending order wrt to element.second and in case the element.second are equal then they are stored in increasing order of element .first
Got your Point…
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.