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 优先级队列
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
