Search code examples
c++priority-queue

What is the correct way of implementing this custom priority_queue


I want to build a priority queue of an object having three elements having my own comparator. I tried the following code but is showing error .


#include<bits/stdc++.h>
using namespace std;


class triplet {
    public:    
        int data;
        int arr;
        int index;       
};

bool compare( triplet x, triplet y ){

    if(x.data < y.data){
        return true;
    }
    else{
        return false;
    }
}

int main(){

 priority_queue<triplet,vector<triplet>,compare> pq1;

}

getting the following error enter image description here


Solution

  • Comparison routines must return false if the two elements are equal, but your version returns true.

    Try this instead

    bool compare(triplet x, triplet y) {
    
        if (x.data < y.data) {
            return true;
        }
        else {
            return false;
        }
    }
    

    or to make it a little simpler like this

    bool compare(triplet x, triplet y) {    
        return x.data < y.data;
    }
    

    But the important point is < not <=.

    EDIT

    Your code also uses compare incorrectly. compare is not a type, so it's not a valid argument for the priority_queue template.

    The type of compare is bool (*)(triplet, triplet) so the right way to do this is to use that type in the template and pass the actual comparison function to the constructor. Like this

    priority_queue<triplet, vector<triplet>, bool (*)(triplet, triplet)> pq1(compare);
    

    BTW normally you would do this by creating a comparison functor, not a function. It's a little cleaner that way (and potentially more efficient).