【问题标题】:Accessing first element in Priority Queue c++访问优先队列c ++中的第一个元素
【发布时间】: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


    【解决方案1】:

    您的错误是 .display() 不是常量成员函数。
    应该是:

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

    顺便说一句,只有在可能需要显式刷新时才使用std::endl,因为它会将所有对良好性能的希望付诸东流。

    另请阅读:Why is "using namespace std" considered bad practice?

    【讨论】:

      【解决方案2】:

      首先,std::priority_queue::front 不存在。我们就是不能调用不存在的东西。

      其次,保持常量正确。声明你的成员函数const

      void display() const
      {...}
      

      这是因为std::priority_queue::top 的返回类型是一个常量引用。通过 const 引用(和 const 值),只能使用 const 成员函数。在const成员函数内部,对象是不能被修改的,这就是const的意思。

      【讨论】:

      • 好吧,你会因为写更多关于 const-correctness 的内容而获得支持。
      【解决方案3】:

      std::priority_queue::front 不存在。 采用 std::priority_queue::top

      是的,函数 display() 应该是其他成员提到的 const :)

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

      【讨论】:

      • 每个人都会遇到。我澄清了这个问题,但是除非您看到一种方法可以添加其他答案中没有的其他内容,否则保留它不会那么有用...
      • 实际上我错过了有问题的顶部,发现没有人在谈论它
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 2012-03-28
      相关资源
      最近更新 更多