I'm having a lot of trouble getting my priority queue to recognize which parameter it should sort by. I've overloaded the less than operator in my custom class but it doesn't seem to use it. Here's the relevant code:
Node.h
class Node
{
public:
Node(...);
~Node();
bool operator<(Node &aNode);
...
}
Node.cpp
#include "Node.h"
bool Node::operator<(Node &aNode)
{
return (this->getTotalCost() < aNode.getTotalCost());
}
getTotalCost() returns an int
main.cpp
priority_queue<Node*, vector<Node*>,less<vector<Node*>::value_type> > nodesToCheck;
What am I missing and/or doing wrong?
C++ Software Engineering The priority queue in the STL of C++ is a dynamically resizing container to implement the special case of priority queye under the queue data structure. It is a sequential linear container. The top element of the priority queue is the greatest with all elements arranged in non-increasing order.
You may have often come to a situation when you need to use a priority queue, but your datatype is something else that can't be compared by default (using '<' operator what is used by default). In such cases, we need to declare our comparator function. We can use the lambda function for that.
A PriorityQueue is what is called a binary heap. It is only ordered/sorted in the sense that the first element is the least. In other word, it only cares about what is in the front of the queue, the rest are "ordered" when needed.
The C++ standard library defines a class template priority_queue, with the following operations: push: Insert an element into the prioity queue. top: Return (without removing it) a highest priority element from the priority queue. pop: Remove a highest priority element from the priority queue.
less<vector<Node*>::value_type>
Means that your comparator compares the pointers to each other, meaning your vector will be sorted by the layout in memory of the nodes.
You want to do something like this:
#include <functional>
struct DereferenceCompareNode : public std::binary_function<Node*, Node*, bool>
{
bool operator()(const Node* lhs, const Node* rhs) const
{
return lhs->getTotalCost() < rhs->getTotalCost();
}
};
// later...
priority_queue<Node*, vector<Node*>, DereferenceCompareNode> nodesToCheck;
Note that you need to be const-correct in your definition of totalCost
.
EDIT: Now that C++11 is here, you don't need to inherit from std::binary_function anymore (which means you don't need to #include functional)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With