LKM
LKM

Reputation: 2450

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!

enter image description here

Upvotes: 0

Views: 1471

Answers (2)

R Sahu
R Sahu

Reputation: 206607

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;

Upvotes: 3

vitaut
vitaut

Reputation: 55564

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) {
  // ...
}

Upvotes: 4

Related Questions