tags:

views:

71

answers:

2

How do I delete all elements from a priority queue? That means how do I destroy a priority queue? advanced thanks for your answer. Is there any clear- or erase-like method?

A: 

As any C++ STL reference will show you, the STL Priority Queue class does not have a function like 'clear' or 'erase'. http://www.cplusplus.com/reference/stl/priority_queue/

It is a container class, and as such, a very simple destructor is generated by the compiler (in most cases). If your priority queue uses only locally-allocated information in its nodes, then this should work fine for clearing out the memory.

However, if you have dynamically allocated memory for the information in your priority queue, you will need to manually create a 'clear'-like function.

Hope this helps!

HokieTux
In C++ "static" is not the opposite of "dynamic". The items in a PQ will not be allocated statically.
anon
Ah - good call on my misnomer =)
HokieTux
+3  A: 

The priority_queue interface doesn't have a clear() method (for no good reason I've ever been able to discern). A simple way to clear it is just to assign a new, empty queue:

priority_queue <int> q;
// use it
q = priority_queue <int>(); // reset it
anon
this works with Queue,but not with priority queue.
russell
@russell What makes you think that? All Standard Library containers and adaptors are assignable.
anon
@Neil: If the priority queue was a container of pointers, wouldn't the owner have to delete each element?
andand
@andand Sure, but the same is true for queues. And in either case you probably want a queue of smart pointers, in which case the problem (probably) goes away.
anon
@Neli: oh,sorry.it works,it was my mistake.thanx for ur help.
russell