简体   繁体   中英

In c++, how to change the position of elements in a vector and do the same changes to an other different vector?

I have 2 vectors, y and T initially of the same size, and they need to stay separated like this. I do a loop until T is empty and every time it loops, the first element of T is used for an algorithm and then erased from the vector T and pushed into vector S (which is empty at first). Every loop, some values in vector y will change and I need to sort them. My problem is: when I sort y, if y[2] and y[3] swap, I need to swap the elements in T that were at [2] and [3] BEFORE the first loop!

I know this seems weird but this is for a Dijkstra algorithm for my Graph project. I understand if it's not clear and I'll try to clarify if you need it. Any advice will be very helpful for me! Thank you!

If I follow you correctly, T is really a FIFO queue. The first element in it each iteration is being 'popped off the front' and placed elsewhere.

Should you be doing this and want at any time to know an ordering of T which includes the elements that were popped off, perhaps you could not remove them from T at all. Just have an iterator or pointer to the next node to be processed.

That node could either be copied to S, or perhaps S would just contain pointers to the node if it were expensive to copy.

This way you're never actually removing the element from T, simply moving on to look at the next item. Presumably it could be cleaned up at the end.

For the Dijkstra algorithm , you usually use a binary heap to implement a priority queue and visit nodes in ascending order of distance to source nodes. At each visit, neighboring distances may be updated ( relax operation) so corresponding queue elements change priority ( decrease-key operation).

Instead of using the distance directly as the key of heap elements, use the node identifier (or pointer). But also use a comparison function (as eg in std::make_heap and most STL algorithms) that, given two node identifiers, compares the corresponding distances.

This way, node identifiers are re-ordered according to heap operations and, whenever you pop an element from the heap (having minimal distance), you can access any information you like given its node identifier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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