A BIG MISCONCEPTION ABOUT PRIORITY_QUEUE

Hello to all!! Here's a doubt about priority_queue which i have since many days, I tried to figure it out on my own but could not figure it out perfectly. We all are familiar with custom functions that we can write for priority_queue.*

I just implemented a question wherein we needed to figure out k nearest elements to a given value and I used priority_queue pq for that having cmp as custom function.
I also tested by making a simple priority_queue where in i wanted all elements to be in descending order(I KNOW BY DEFAULT PRIORITY_QUEUE DOES SO, BUT I WANTED TO IMPLEMENT IT BY MYSELF) , in cmp1 i wrote a condition that return a> b, which in my understanding means that if a is greater than b should have more priority and should come before b.

But i got the result to be opposite. I also got confused that "maybe we have to write opposite condition in custom function. But in the 1st priority_queue i wrote the conditions as it is to get k nearest neighboours and got result to be right.

So can somebody help me out with this confusion whether we need to write opposite condition in the custom function or the actual condition?

This is the code below:

struct cmp
{
bool operator()(pair<int,int>a,pair<int,int>b)
{
return a.first<b.first || (a.first == b.first && a.second < b.second) ;
}
};

struct cmp1
{
bool operator()(int &a,int &b)
{
return a>b;
}
};
class Solution {
public:
vector findClosestElements(vector& a, int k, int x) {

    priority_queue<pair<int,int>,vector<pair<int,int> >, cmp>pq;
    int i,n=a.size();
    for(i=0;i<k;i++)
    {
        int diff = abs(a[i]-x);
        pq.push({diff,a[i]});
    }
    
    for(i=k;i<n;i++)
    {
        int diff = abs(a[i]-x);
        if(pq.top().first > diff)
        {
            pq.pop();
            pq.push({diff,a[i]});
        }
    }
    
    vector<int>ans;
    
    while(!pq.empty())
    {
        ans.push_back(pq.top().second);
        pq.pop();
    }
    sort(ans.begin(),ans.end());
    
    priority_queue<int,vector<int>,cmp1>pq1;
    pq1.push(3);
    pq1.push(1);
    pq1.push(32);
    pq1.push(12);
    pq1.push(55);
    
    while(!pq1.empty())
    {
        cout<<pq1.top()<<" ";
        pq1.pop();
    }
    
    return ans;
}

};

OUTPUT
for second priority_queue 1 3 12 32 55
OUTPUT FOR INPUT [0,0,1,2,3,3,4,7,7,8]
k=3
x=5

Getting correct output
Output
[3,3,4]
Expected
[3,3,4]

Comments (0)