STL Priority Queue on custom class(自定义类上的 STL 优先级队列)
问题描述
我在让我的优先队列识别它应该按哪个参数排序时遇到了很多麻烦.我在自定义类中重载了小于运算符,但它似乎没有使用它.相关代码如下:
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 优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:自定义类上的 STL 优先级队列
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
