[英]How to write comparator class for STL priority queue?
这是我的两个班
class Graph
{
private:
unordered_map<int, Vertex> _vertices;
};
class Vertex
{
private:
unordered_map<Vertex *, int> _edges;//key: pointer to a vertex, data: edge weight from this vertex to a certain vertex
int _load_factor = 0;
int _id = 0;
};
如果要使用Dijkstra的算法来计算某一遍的最短路径,则需要使用优先级队列。 我不知道如何为以下对象编写比较器类:
priority_queue<Vertex, vector<Vertex>, PathWeightComparer> dijkstra_queue{};
这是我在网上找到的:
class PathWeightComparer
{
public:
bool operator()(Vertex lhs, Vertex rhs)
{
return (lhs.getPathWeight() > rhs.getPathWeight());
}
};
lhs和rhs是指什么? 是priority_queue
的顶点吗? 如果要获得此比较的路径权重,我需要知道从哪里到因素。 我可以只创建一个新的变量名_path_weight
并将其仅用于findShortestPath()
吗? 我不明白的主要是lhs和rhs的概念,它们是什么? 还有一件事,我当前的比较器类将导致最大堆还是最小堆?
非常感谢
std::priority_queue
的要点是为您提供由比较器功能选择的最高优先级(最大,最小等)的常量访问时间。
lhs
和rhs
是指什么?
那就是你的比较方式。 将两个元素传递给比较器函数,以确定哪个元素比另一个元素“优越”(或具有更高的优先级)。 比较就是我们所说的二进制操作(两个操作数),对吗?
我当前的比较器类将导致最大堆还是最小堆?
您正在与>
进行比较,从而获得最大堆。
最后,正如我评论的那样,签名应为:
bool operator()(Vertex const& lhs, Vertex const& rhs);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.