问题描述
我在让我的优先队列识别它应该按哪个参数排序时遇到了很多麻烦.我在自定义类中重载了小于运算符,但它似乎没有使用它.相关代码如下:
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() 返回一个整数
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?
推荐答案
less 表示你的比较器比较指针彼此之间,这意味着您的向量将按节点内存中的布局进行排序.
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.
你想做这样的事情:
#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;
请注意,您需要在 totalCost 的定义中保持常量正确.
Note that you need to be const-correct in your definition of totalCost.
既然 C++11 已经出现,您就不再需要从 std::binary_function 继承(这意味着您不需要 #include 函数式)
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)
这篇关于自定义类上的 STL 优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)