Please read the new rule regarding the restriction on the use of AI tools. ×

vedprakashsingh216's blog

By vedprakashsingh216, history, 21 month(s) ago, In English

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

  • Vote: I like it
  • 0
  • Vote: I do not like it