自定义类上的 STL 优先级队列
我在让优先级队列识别它应该按哪个参数排序时遇到了很多麻烦。我已经在自定义类中重载了小于运算符,但它似乎没有使用它。这是相关代码:
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;
我错过了什么和/或做错了什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
less::value_type>
表示您的比较器将指针相互进行比较,这意味着您的向量将按照该向量在内存中的布局进行排序节点。您想要执行如下操作:
请注意,您的
totalCost
定义需要保持常量正确。编辑:现在 C++11 已经到来,您不再需要从 std::binary_function 继承(这意味着您不需要 #include 函数)
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:
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)
您需要将参数设置为 const,因为现在您正在为其提供非成本引用,这意味着您可能会修改要比较的对象。 (你不是,而且可能不应该)。
你没有保持常量正确。您的
operator<
不会对 Node 进行修改,因此该函数应该是 const:此后,如果您在调用
getTotalCost()
函数时遇到问题,很可能是它也不是const。如果尚未将其标记为 const:您的代码现在(更)是 const 正确的。
附带说明一下,二元运算符通常在类外部实现:
You need to make your parameter
const
, because as of now you're giving it a non-cost reference, which means you might modify the object you're comparing with. (Which you aren't, and probably shouldn't).You're not being const-correct. Your
operator<
doesn't make modifications to the Node, so the function should be const:After that, if you have trouble calling the
getTotalCost()
function, it's likely that it is not const as well. Mark it as const if it's not already:Your code is now (more) const-correct.
On a side note, binary operators are usually implemented outside the class: