【发布时间】:2015-11-19 06:04:54
【问题描述】:
我正在开发需要使用优先级队列的程序。据我了解,优先级队列会自动从最大到最小元素对队列进行排序。我创建了一个简单的对象(节点)优先级队列,具有名称和 ID 号。我试图访问队列中的第一个对象,所以我想我可以只使用“front”成员函数。这在我使用标准队列时有效,但当我使用优先级队列时出现错误
错误:“class std::priority_queue”没有名为“front”的成员
我也尝试使用“top”,但随后出现错误
错误:将 'const value_type (aka const node)' 作为 'this' 参数传递 'void::display()' 丢弃限定符 [-fpermissive]
这是我的代码:
#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
}
我将再次指出,如果我使用队列而不是优先级队列,则代码可以工作。如何访问优先级队列的前端?
【问题讨论】:
标签: c++ constants priority-queue const-correctness