Search code examples
c++constantspriority-queueconst-correctness

Accessing first element in Priority Queue c++


I am working on program in which I am require to use a priority queue. From my understanding the priority queue sorts the queue automatically from largest to smallest elements. I have create a simple priority queue of objects(nodes) that have a name and id number. I am trying to access the first object in the queue so I figured I could just use the "front" member function. This works when I use the standard queue but when I use a priority queue I get the error

error: 'class std::priority_queue' has no member named 'front'

I tried using "top" as well but then I get the error

error: passing 'const value_type (aka const node)' as 'this' argument of 'void::display()' discards qualifiers [-fpermissive]

here is my code:

#include <iostream>       
#include <queue>          

using namespace std;

struct node
{
    node(char n, int i) { name = n; id = i; }
    void display() { cout << "name: " << name << "   id : " << id << endl; }
    friend bool operator < (node a, node b) { return a.id < b.id; }
private:
    char name;
    int id;
};

int main()
{
  queue<node> myqueue; // Actually want a priority_queue<node>

  myqueue.push(node('a',5));
  myqueue.push(node('b',9));
  myqueue.push(node('c',7));

  myqueue.front().display(); // Error when using the type I want, even if I call top() instead
}

I will point out again that if I use queue instead of priority queue the code works. How do I access the front of a priority queue?


Solution

  • Your error is that .display() is not a constant member-function.
    It should be:

    void display() const { std::cout << "name: " << name << "   id : " << id << '\n';}
    

    As an aside, only use std::endl if explicitly flushing might be neccessary, as it flushes all hope of good performance down the drain.

    Also read: Why is "using namespace std" considered bad practice?