Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge two priority queues [duplicate]

std::priority_queue<some_type, std::vector<some_type>, some_comparator> A;
std::priority_queue<some_type, std::vector<some_type>, some_comparator> B;

How can I merge these priority queues A and B based on same comparator. I tried to find builtin function but could not find any.

like image 278
Utkrist Adhikari Avatar asked Jul 19 '13 11:07

Utkrist Adhikari


People also ask

Is duplicates allowed in priority queue?

Answer: Yes. Priority Queue allows duplicate values.

Does priority queue remove duplicates?

PriorityQueue allows duplicates. So if you want to avoid that, you need to implement your own version of Queue. You can find very elegant way, how to do that in "Effective Java", page 85.

What happens if two elements have the same priority in priority queue?

If two elements in a priority queue have the same priority, they will be arranged using the FIFO principle.


1 Answers

The simplest way is to simply move objects from one queue to another:

while(!B.empty()) {
    A.push(B.top());
    B.pop();
}

There might exist a more efficient method, though.

like image 70
zch Avatar answered Sep 22 '22 03:09

zch