Reputation: 57
my problem is:
I have my program with 2 class plus the main;
I've declared a priority_queue inside a member function of a class;
I have to define the comparison and I think the code I should use is:
// Determine priority (in the priority queue)
bool operator < (const node & a, const node & b)
{
return a.getPriority() > b.getPriority();
}
Question: where Should I insert this piece of code? Could someone help me?
thanks
Upvotes: 0
Views: 2220
Reputation: 28178
It looks like your operator<
is possibly a poor addition to node
. Ask yourself: are nodes logically comparable? Is it clear that comparing nodes (outside of the context of priorty_queue) should compare their priority? Maybe it should compare their position, or anything else they might contain. If you supply an operator<
it will also make sense to have the other 5 comparison operators. If it's not clear what node < node
actually compares, don't provide an operator<
for nodes. In cases like this it's better to provide a custom comparer to the priority_queue
...
struct NodeComparer
{
bool operator()(const node& left, const node& right)
{
return left.GetPriority() > right.GetPriority();
}
}
...
std::priority_queue<node, std::vector<node>, NodeComparer> nodeQueue;
This way your priority_queue
can work as desired but you don't add illogical functionality to node
.
Upvotes: 1
Reputation: 71019
This operator should be visible where the priority_queue is declared. As the priority queue exists only in a member I would place the operator's definition right above the given method definition in the .cpp
file that implements the method.
Upvotes: 0