[英]priority_queue declaration and bool operator < declaration
my problem is: 我的问题是:
I have my program with 2 class plus the main; 我的课程有2节课加上主课;
I've declared a priority_queue inside a member function of a class; 我已经在类的成员函数中声明了priority_queue;
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 谢谢
It looks like your operator<
is possibly a poor addition to node
. 看来您的
operator<
可能对node
补充很差。 Ask yourself: are nodes logically comparable? 问自己:节点在逻辑上是否可比? Is it clear that comparing nodes (outside of the context of priorty_queue) should compare their priority?
是否清楚比较节点(在Priority_queue上下文之外)应该比较其优先级? 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. 如果您提供一个
operator<
那么另选5个比较运算符也很有意义。 If it's not clear what node < node
actually compares, don't provide an operator<
for nodes. 如果不清楚哪个
node < node
实际比较,请不要为节点提供operator<
。 In cases like this it's better to provide a custom comparer to the priority_queue
... 在这种情况下,最好为
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
. 这样,您的
priority_queue
可以按需工作,但不会向node
添加不合逻辑的功能。
This operator should be visible where the priority_queue is declared. 在声明priority_queue的位置,该操作符应该可见。 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. 由于优先级队列仅存在于成员中,因此我将运算符的定义放在实现该方法的
.cpp
文件中给定方法定义的上方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.