Domanda

I am trying to implement Dijkstra's shortest path algorithm using C++ and STL. Since STL's priority queues do not support a decrease-key operation, I decided to use regular ordered sets. 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). 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?

Are there any other flaws that you guys can think of? Or do you perhaps have some better ideas than using std::set?

Have a great Sunday, everyone.

È stato utile?

Soluzione

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. 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).

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. To me it seems as if the first point would be the problem here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top