user3920913
user3920913

Reputation: 125

"No matching member function for call to push" in Priority Queues 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));

Upvotes: 4

Views: 9548

Answers (2)

Alexander Mei&#223;ner
Alexander Mei&#223;ner

Reputation: 826

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);
}

Upvotes: 4

Vinayak Garg
Vinayak Garg

Reputation: 6616

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

Upvotes: 3

Related Questions