Search code examples
c++priority-queue

Is it possible to change from which "side" objects are added in the priority queue with the same priority?


I am using std::priority_queue with some custom objects inside std::vector. Now suppose I have objects with the same priority when I call top() function I get them in order from oldest to the newest. So my question is it possible to change this behavior so top() would return the most recent object in the case of equal priority?


Solution

  • An easy (but finite) solution is to keep a counter, and use the counter's value at insertion as a secondary key for otherwise equal objects. Counting down instead of up will reverse the priority order.

    Finite because the counter might wrap, but with long long that's not a big risk.