Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"No matching member function for call to push" in Priority Queues C++

Tags:

c++

I'm trying to implement a priority queue right now, but I keep getting an error saying that push is not a member function. I never used priority queue before, so I'm pretty sure I'm messing up somewhere...

struct X
{
    unordered_map<string, double> distance;
    unordered_map<string, string> vertices;
};

void make(std::string source)
{
    X distance;
    X parent;
    priority_queue<X, std::vector<X>, greater<void>> pq; //i'm pretty sure there's something wrong with the templates?
    distance.distance[source] = 0;
    pq.push(std::make_pair(start, 0));
like image 475
user3920913 Avatar asked Oct 15 '25 02:10

user3920913


2 Answers

The class has to be comparable and must respond to operators like < and > so that the queue can sort them:

class X {
    public:
    unordered_map<string, double> distance;
    unordered_map<string, string> vertices;
    int priority;
    bool operator< (const X& b) {
        return priority < b.priority;
    }
    bool operator> (const X& b) {
        return priority > b.priority;
    }
};

void make(std::string source) {
    priority_queue<X, vector<X>, greater<void>> pq;

    X element;
    element.distance[source] = 0;
    element.priority = 100;
    pq.push(element);
}
like image 65
Alexander Meißner Avatar answered Oct 17 '25 19:10

Alexander Meißner


The push expects (and accepts) parameter of type X, while you are passing something else (a pair).

like image 35
Vinayak Garg Avatar answered Oct 17 '25 20:10

Vinayak Garg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!