Jan Berndt
Jan Berndt

Reputation: 1055

Change sorting function of priority queue during runtime

I have a std::priority_queue with a custom sorting function. At a point in the program, I want to reorganize the queue using a different function.

Is this possible? Or can I make a pointer to the queue that I can point to a differently sorted queue when needed?

Upvotes: 0

Views: 808

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409166

The important part here is to not think of ordered containers like std::priority_queue as sorted, because they really aren't. Instead they are, as the name implies, ordered. And the ordering is only done by putting new elements in their ordered place when they are actually inserted into the container. There's no reordering of the containers.

Therefore it's not really possible to change ordering at run-time, because all the existing elements in the queue will still be ordered the way they were when inserted, and new elements might not be placed in the correct place because the ordering is no longer correct.

The only way to reorder a std::priority_queue is to create a new queue with the new ordering function, and then copy the elements from the old to the new queue.

Upvotes: 1

Hatted Rooster
Hatted Rooster

Reputation: 36463

That's not possible as the Compare function given to the priority_queue is a template type, this means that the Compare itself belongs to that type.

These:

std::priority_queue<int, std::vector<int>, std::less<int>>;
std::priority_queue<int, std::vector<int>, std::greater<int>>;

While looking similar are 2 different types.

What you can do is adapt your Compare function to look at some external state and sort based on that.

Upvotes: 1

Related Questions