0
votes

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?

3

3 Answers

3
votes

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?

2
votes

Firstly, std::priority_queue::front does not exist. We just can't invoke something doesn't exist.

Secondly, be const-correct. Declare your member functions const.

void display() const
{...}

This is because the return type of std::priority_queue::top is a const reference. Via a const reference (and const value), only const member functions can be used. Inside a const member function, the object cannot be modified, which is the meaning of being const.

0
votes

std::priority_queue::front does not exist. Use std::priority_queue::top

And yes, function display() should be const as mentioned by fellow member :)

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