I had a solution to a problem which included priority queue.
I wish to know if we can change the comparator of priority queue at run time like if we initially had the declaration as priority_queue<int> pq which will store no.s in non-increasing order, can I use the same priority queue to store no.s in increasing order after pq.clear()
Thanks









AFAIK there is no clear method for
priority_queuein C++. What you can do is naively pop elements out or create a newpriority_queue:Now comeback to your question, I haven't seen anyway to change the comparator. However there is a simple workaround using custom comparator.
Output:
With
signequal to-1, small numbers will be prioritized and similar forsignequal to1does the comparator swaps element on the condition being true here?
as with normal comparators with a = 1 and b = 2 and sign = -1, a*sign < b*sign returns false and swaps them..
is the thing opposite here? as it seems that the order of the two elements being compared remains same when the condition is false.
Order of elements in a
priority_queueis reversed.For example
is actually a minheap.
For the case $$$a = 1$$$, $$$b = 2$$$ and $$$sign = -1$$$, the comparator return false, but it should be reversed so the order remain the same.
It is possible but you will have to maintain the
priority_queuemanually usingmake_heap,push_heap, andpop_heap.https://ideone.com/jBJc9w
To change the comparator of the
std::proiority_queue, you may use a type of struct/class calledfunctor. It is a struct/class which has a functionoperator().For example, to use a heap that its top element is the smallest one. You can write as follows.
There is already functors in STL called
greater<T>andless<T>. Code above can also write as follows:If you found mistakes in my code, please comment me.
And forgive me for my poor English.