0
votes

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

2
I found that I have to override method operator method... but when and how should I do that? - LKM
The problem in the code which is not shown here. - Eugene Sh.
You cannot possibly be receiving this error when you run the project. You must be receiving it when you compile the project. - Mike Nakis
Please show us the code that causes the problem, otherwise we can only guess. - 463035818_is_not_a_number
You don't have a comparator. Either operator<, or a functor. Have a look at this - dmg

2 Answers

4
votes

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

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;