简体   繁体   中英

C++ ) Invalid operands to binary expression Error with Priority Queue

I have a struct(A) and Priority Queue(PQ) at another struct(B).

This is struct A below :

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?

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):

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 .

You can define the operator< overload as a member function or a non-member function.

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

You can also use a Compare class that provides the ability to compare two Node objects:

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

and use it to construct std::priority_queue object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM