Need help with custom comparator in priority queue

Правка en3, от apjcoder123, 2022-02-26 20:19:00

I am trying to learn about custom comparators in priority queue. however, i am unable to get the expected behaviour. I have wrote two custom comparators in the below code one for a vector and the other for a priority queue and the logic is same for both the comparators. how the output seems to be opposite, can anyone tell me the reason for this, any help will be appreciated.

In my thinking the output given by the priority queue should be same as the vector but it isn't.

Actual Ouput:

Vector: 1 6 2 5 2 4

Priority Queue: 2 4 2 5 1 6

Expected Output:

Vector: 1 6 2 5 2 4

Priority Queue: 1 6 2 5 2 4

struct cmp1 {
    bool operator()(pii const& a,pii const& b)
    {
        if(a.first==b.first) return a.second>b.second;
        return a.first<b.first;
    }
};

bool cmp2(pii const& a,pii const& b)
{
    if(a.first==b.first) return a.second>b.second;
    return a.first<b.first;
}

int main()
{
    priority_queue<pii,vector<pii>,cmp1> cust_heap;
    cust_heap.push({1,6});
    cust_heap.push({2,4});
    cust_heap.push({2,5});
    
    vector<pii> v;
    v.push_back({1,6});
    v.push_back({2,4});
    v.push_back({2,5});
    
    sort(v.begin(),v.end(),cmp2);
    
    cout<<"Vector: "<<'\n';
    
    for(auto x:v) cout<<x.first<<" "<<x.second<<'\n';
    
    cout<<'\n';
    
    cout<<"Priority Queue: "<<'\n';
    
    while(!cust_heap.empty())
    {
        int freq=cust_heap.top().first;
        int element=cust_heap.top().second;
        cust_heap.pop();
        cout<<freq<<" "<<element<<'\n';
    }
    
    cout<<'\n';
    
    return 0;
}

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en3 Английский apjcoder123 2022-02-26 20:19:00 21
en2 Английский apjcoder123 2022-02-26 20:15:42 377
en1 Английский apjcoder123 2022-02-26 20:12:13 1814 Initial revision (published)