【问题标题】:C++ ) Invalid operands to binary expression Error with Priority QueueC++ ) 二进制表达式的无效操作数 优先级队列错误
【发布时间】:2015-12-03 16:46:10
【问题描述】:

我在另一个 struct(B) 上有一个 struct(A) 和 Priority Queue(PQ)。

这是下面的结构A:

struct Node{
int level;
int total;
std::vector<int> sequence;

void clear(){
    sequence.clear();
}

void init(){
    level = 0;
    total = 0;
    sequence.clear();
}

long subjectNumber(){
    return sequence.size();
}

bool isInSequence(int index){
    for(int i = 0; i < sequence.size(); i++){
        if(index == sequence.at(i)){
            return true;
        }
    }
    return false;
}};

没什么特别的吧?

我使用节点对象的优先级队列,如下所示:

    std::priority_queue<Node> pq;

但是当我运行项目时出现错误:

二进制表达式的无效操作数('const Node' 和 'const Node')

我想把Node对象的总价值放在首位 我该如何解决这个问题?

UPDATED:
The picture is what I'm getting, at the project, there is no 'red'Line for me!

【问题讨论】:

  • 我发现我必须重写方法运算符方法...但是我应该何时以及如何做到这一点?
  • 代码中的问题,这里没有展示。
  • 您在运行项目时不可能收到此错误。您必须在编译项目时收到它。
  • 请告诉我们导致问题的代码,否则我们只能猜测。
  • 您没有比较器。 operatorthis

标签: c++ priority-queue invalidoperationexception


【解决方案1】:

std::priority_queue 要求元素类型提供重载的operator&lt;(或通过Compare 模板参数提供的比较器):

bool operator<(const Node& lhs, const Node &rhs) {
  // ...
}

【讨论】:

  • 好的,谢谢@vitaut!但是我可以在哪里以及如何做到这一点?
  • 您可以将operator&lt;函数重载为成员函数或非成员函数。
  • @RSahu 我应该在 structA (== struct Node) 处重载吗?
  • @RSahu 谢谢你,但是 R,当我在 struct Node 中编写该方法时,我得到一个错误:Overloaded 'operator
  • @LKM,当它是成员重载时,您必须使用bool operator&lt;(const Node&amp; rhs) const;。当它是非成员重载时,您必须使用答案中使用的语法。
【解决方案2】:

为了能够使用std::priority_queue&lt;Node&gt;,您需要Node 的有效小于运算符函数。

您可以将operator&lt; 重载定义为成员函数或非成员函数。

成员函数重载

struct Node{
   int level;
   int total;
   std::vector<int> sequence;

   void clear(){
      sequence.clear();
   }

   bool operator<(Node const& rhs) const { ... }
};

非成员函数重载

struct Node{
   int level;
   int total;
   std::vector<int> sequence;

   void clear(){
      sequence.clear();
   }

};

bool operator<(Node const& lhs, Node const& rhs) { ... }

使用Compare

您还可以使用Compare 类,它提供了比较两个Node 对象的能力:

struct NodeCompare
{
    bool operator()(Node const& lhs, Node const& rhs) { ... }
};

并用它来构造std::priority_queue对象。

using MyQueue = std::priority_queue<Node, NodeCompare>;
MyQueue queue;

【讨论】:

  • @R Sahu 兄弟,你告诉我的工作但并不完美我认为重载的方法运算符只是涵盖了“两个”Node 对象的比较......这不是问题吗?在我的程序中经常会发现异常
  • @LKM,这是priority_queue需要的核心功能。很难说出引发异常的原因是什么。请使用Minimal, Complete, and Verifiable example 创建另一个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多