简体   繁体   English

使用C ++和STL实现Dijkstra的最短路径算法

[英]Implementing Dijkstra's shortest path algorithm using C++ and STL

I am trying to implement Dijkstra's shortest path algorithm using C++ and STL. 我正在尝试使用C ++和STL实现Dijkstra的最短路径算法。 Since STL's priority queues do not support a decrease-key operation, I decided to use regular ordered sets. 由于STL的优先级队列不支持减少键操作,因此我决定使用常规的有序集。 My algorithm is almost identical to this one . 我的算法几乎与算法相同。

However , I have some concerns. 但是 ,我有些担心。 Namely, the ordering of the edges in the set will depend both upon the vertex number of the destination and the weight (as the regular relational operators of std::pair will be used). 也就是说,集合中边的排序将取决于目标的顶点数和权重(因为将使用std::pair常规关系运算符 )。 I do believe that it should only depend on the weight. 我确实相信它应该仅取决于重量。 If I were to declare the set by using a custom comparator which would compare only the weights, how would I make std::set::erase work, as it is needed to erase the edges between the same vertices but with greater weight? 如果我要通过使用仅比较权重的自定义比较器来声明集合,我将如何使std::set::erase工作,因为需要擦除相同顶点之间的边但权重更大?

Are there any other flaws that you guys can think of? 你们还有其他缺陷可以想到吗? Or do you perhaps have some better ideas than using std::set ? 还是您可能比使用std::set有更好的主意?

Have a great Sunday, everyone. 祝大家星期天愉快。

Your question seem to confuse the technical implementation and the algorithm. 您的问题似乎混淆了技术实现和算法。

First, on the technical side, for std::set you seem to need a special ordering as well as an erasement of certain elements. 首先,在技术方面,对于std :: set,您似乎需要特殊的排序以及某些元素的删除。 The ordering can be changed by a custom comparator, for example see here . 可以通过自定义比较器更改顺序,例如,请参见此处 However, I would not order only by the weights, as there might be duplicates. 但是,我不会仅按权重排序,因为可能会有重复项。 Just put the weights in the component of std::pair which has a higher priority (--the first component). 只需将权重放在具有更高优先级的std::pair组件中(第一个组件)。

Next, in order to erase an element, you must first be sure which one, which is done by providing an iterator pointing to that element. 接下来,为了擦除元素,必须首先确定哪个元素,方法是提供指向该元素的迭代器。 This step is not at all influenced by your custom comparison function. 此步骤完全不受您的自定义比较功能的影响。

Quickly summarizing: you should (i) find out which elements need to be erased exactly, (ii) find the corresponding iterators via std::set::find and (iii) erase them. 快速总结:您应该(i)找出需要精确擦除的元素,(ii)通过std::set::find相应的迭代器,以及(iii)擦除它们。 To me it seems as if the first point would be the problem here. 在我看来,似乎第一点就是这里的问题。

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

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