简体   繁体   English

如何为STL优先级队列编写比较器类?

[英]How to write comparator class for STL priority queue?

This is the two classes I have 这是我的两个班

    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;
    };

If I want to use Dijkstra's algorithm to compute the shortest path from a certain pass, I need to use a priority queue. 如果要使用Dijkstra的算法来计算某一遍的最短路径,则需要使用优先级队列。 I have no Idea how can I write a comparator class for: 我不知道如何为以下对象编写比较器类:

priority_queue<Vertex, vector<Vertex>, PathWeightComparer> dijkstra_queue{};

This is what I found online: 这是我在网上找到的:

class PathWeightComparer
{
public:
    bool operator()(Vertex lhs, Vertex rhs)
    {
        return (lhs.getPathWeight() > rhs.getPathWeight());

    }
};

What is lhs and rhs refer to? lhs和rhs是指什么? Is it the vertices from the priority_queue ? priority_queue的顶点吗? If so to get a path weight for this comparison, I need to know where from to factors. 如果要获得此比较的路径权重,我需要知道从哪里到因素。 Can I just create a new variable name _path_weight and only use it for findShortestPath() ? 我可以只创建一个新的变量名_path_weight并将其仅用于findShortestPath()吗? The main thing I don't understand is the notion of lhs and rhs, what are they? 我不明白的主要是lhs和rhs的概念,它们是什么? One more thing, my current comparator class will result in max heap or min heap? 还有一件事,我当前的比较器类将导致最大堆还是最小堆?

Thank you so much 非常感谢

The point of std::priority_queue is to give you a constant access time of the element of the highest priority that is chosen by the comparator function (the largest, the smallest, etc.). std::priority_queue的要点是为您提供由比较器功能选择的最高优先级(最大,最小等)的常量访问时间。

What is lhs and rhs refer to? lhsrhs是指什么?

That's how you compare. 那就是你的比较方式。 Two elements are passed to the comparator function to determine which one is "superior" over the other (or has greater priority). 将两个元素传递给比较器函数,以确定哪个元素比另一个元素“优越”(或具有更高的优先级)。 Comparison is what we call a binary operation (two operands), right? 比较就是我们所说的二进制操作(两个操作数),对吗?

my current comparator class will result in max heap or min heap? 我当前的比较器类将导致最大堆还是最小堆?

You're comparing with > , thereby max heap. 您正在与>进行比较,从而获得最大堆。

Lastly, as I commented, the signature should be: 最后,正如我评论的那样,签名应为:

bool operator()(Vertex const& lhs, Vertex const& rhs);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM