问题描述
我的问题是:
-
我有我的程序2类加主>
-
我已在类的成员函数中声明了priority_queue;
-
我认为应该使用的代码是:
//确定优先级(在优先级队列中)
bool operator< ; (const node& a,const node& b)
{
return a.getPriority()> b.getPriority();
}
问题:我插入这段代码?
这看起来像是你的运算符<
可能是对节点
的一个不好的补充。问自己:节点是逻辑上可比的?很明显,比较节点(在priorty_queue的上下文之外)应该比较它们的优先级吗?也许它应该比较自己的位置,或任何他们可能包含的东西。如果你提供一个运算符<
,还有其他5个比较运算符也是有意义的。如果不清楚什么节点<节点
实际上进行比较,不为节点提供运算符<
。在这种情况下,最好为 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;
这样,您的 priority_queue
但您不会向节点
添加不合逻辑的功能。
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
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
.
这篇关于priority_queue声明和bool操作符<宣言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!