[英]C++ ) Invalid operands to binary expression Error with Priority Queue
I have a struct(A) and Priority Queue(PQ) at another struct(B). 我在另一个struct(B)上有一个struct(A)和Priority Queue(PQ)。
This is struct A below : 这是下面的结构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;
}};
Nothing special right? 没什么特别的权利吗?
and I use priority queue of Node Objects like below : 我使用如下所示的节点对象的优先级队列:
std::priority_queue<Node> pq;
But when I run the project I got an error : 但是,当我运行项目时,出现错误:
Invalid operands to binary expression ('const Node' and 'const Node') 无效的二进制二进制操作数(“常量节点”和“常量节点”)
I want to put top priority for the total value of Node object How can I solve this problem? 我想把Node对象的总价值放在首位。如何解决这个问题?
UPDATED:
The picture is what I'm getting, at the project, there is no 'red'Line for me!
std::priority_queue
requires that the element type provides an overloaded operator<
(or a comparator via the Compare
template argument): std::priority_queue
要求元素类型提供重载的operator<
(或通过Compare
template参数的Compare
器):
bool operator<(const Node& lhs, const Node &rhs) {
// ...
}
In order to be able to use std::priority_queue<Node>
, you need a valid less than operator function for Node
. 为了能够使用std::priority_queue<Node>
,您需要为Node
一个有效的小于运算符。
You can define the operator<
overload as a member function or a non-member function. 您可以将operator<
重载定义为成员函数或非成员函数。
Member function overload 成员函数重载
struct Node{
int level;
int total;
std::vector<int> sequence;
void clear(){
sequence.clear();
}
bool operator<(Node const& rhs) const { ... }
};
Non-member function overload 非成员函数重载
struct Node{
int level;
int total;
std::vector<int> sequence;
void clear(){
sequence.clear();
}
};
bool operator<(Node const& lhs, Node const& rhs) { ... }
Using a Compare
class 使用Compare
类
You can also use a Compare
class that provides the ability to compare two Node
objects: 您还可以使用Compare
类,该类提供比较两个Node
对象的功能:
struct NodeCompare
{
bool operator()(Node const& lhs, Node const& rhs) { ... }
};
and use it to construct std::priority_queue
object. 并使用它来构造std::priority_queue
对象。
using MyQueue = std::priority_queue<Node, NodeCompare>;
MyQueue queue;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.