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
priority_queue doesn't have a clear method. It may be that this is for interface simplicity, or because it there may be situations in which elements must be destroyed in priority-order, making a generic clear function unsafe.
Regardless, the following code block includes two functions to clear priority queues. The first works by building a temporary instance of a wrapper class around the priority_queue and then using this to access the underlying storage object, which is assumed to have a clear() method. The second works by replacing the existing priority_queue with a new queue.
I use templating so that the functions can be recycled time and again.
#include
#include
using namespace std;
template
void clearpq(priority_queue& q) {
struct HackedQueue : private priority_queue {
static S& Container(priority_queue& q) {
return q.*&HackedQueue::c;
}
};
HackedQueue::Container(q).clear();
}
template
void clearpq2(priority_queue& q){
q=priority_queue();
}
int main(){
priority_queue testq, testq2;
//Load priority queue
for(int i=0;i<10;++i)
testq.push(i);
testq2=testq;
//Establish it is working
cout<