How to use pairs on priority queue and custom function

Revision en1, by vedprakashsingh216, 2022-12-20 11:17:49

How to use pairs on priority queue and custom function

Here in this blog i will take help you to how to implement priority queue on pairs using custom comparators, You will have difficult finding this on internet as it took a lot of effort to find the correct working code which works for -std=++14 compiler of g++.

typedef pair<int, int> pd;

struct myComp {
    bool operator()(
        pair<int, int> &a,
        pair<int, int> &b)
    {
        if(a.first < b.first){
            return true;
        }else if(a.first > b.first){
            return false;
        }else{
            return a.second > b.second;
        }
        return true;
    }
};

void solve(){
    // int q;
    // cin>>q;

    priority_queue<pd, vector<pd>, myComp> p1;

    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        int t1;
        cin>>t1;
        p1.push({t1,i+1});
    }

    while(p1.size() > 0){
        pair<int,int> p2;
        p2 = p1.top();
        p1.pop();
        cout<<p2.first<<" "<<p2.second<<"\n";
    }

This works as you can make changes in the myComp and use it as you want over the pairs Source — https://www.geeksforgeeks.org/priority-queue-of-pairs-in-c-with-ordering-by-first-and-second-element/

Geeks for Geeks

Tags priorityqueue, pairs, comparable, curstomcomparators

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English vedprakashsingh216 2022-12-20 11:17:49 1384 Initial revision (published)