0

I have an algorithm that uses a priority queue to select an element to operate on. However, on each step an O(1) amount of elements in the queue need to have their weights updated.

The standard stl priority queue does not allow for this kind of update. Is there another container in the stl that can be used for this kind of updating?

Makogan
  • 8,208
  • 7
  • 44
  • 112
  • 1
    Is delete + re-add acceptable? – Mark Lavin Oct 11 '21 at 22:03
  • Do you mean popping and then adding what you popped? – Makogan Oct 11 '21 at 22:10
  • 1
    You might be able to use [`std::make_heap`](https://en.cppreference.com/w/cpp/algorithm/make_heap), but you'd have to remake the heap after your updates which might be too time consuming. – 1201ProgramAlarm Oct 11 '21 at 22:14
  • @Makogan, yes, updating the key value before re-adding. – Mark Lavin Oct 11 '21 at 22:17
  • That sounds like it is in O(nlogn) since you might need to pop arbitrarily many objects that ahve not been modified. :\ – Makogan Oct 11 '21 at 23:06
  • Use a plain `std::set`. To update the weight, remove the element with the old weight and re-insert with the new. – Igor Tandetnik Oct 12 '21 at 03:07
  • @IgorTandetnik how would I find an element in the set by weight? Iteration? – Makogan Oct 12 '21 at 03:25
  • 3
    You would use the same comparator for `set` that you use for your `priority_queue`. Then `set::find` could be used to find an element by weight. Alternatively, use `std::map` to make searching by weight more straightforward. `std::multiset` / `std::multimap` if multiple items may have the same weight. – Igor Tandetnik Oct 12 '21 at 03:26
  • Does this answer your question? [Easiest way of using min priority queue with key update in C++](https://stackoverflow.com/questions/9209323/easiest-way-of-using-min-priority-queue-with-key-update-in-c) – Shmil The Cat Jan 04 '22 at 16:34

0 Answers0