Skip to content

priority queue clear method

An answer to this question on Stack Overflow.

Question

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?

Answer

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 <queue>
#include <iostream>
using namespace std;
template <class T, class S, class C>
void clearpq(priority_queue<T, S, C>& q) {
	struct HackedQueue : private priority_queue<T, S, C> {
		static S& Container(priority_queue<T, S, C>& q) {
			return q.*&HackedQueue::c;
		}
	};
	HackedQueue::Container(q).clear();
}
template <class T, class S, class C>
void clearpq2(priority_queue<T, S, C>& q){
	q=priority_queue<T, S, C>();
}
int main(){
	priority_queue<int> testq, testq2;
	//Load priority queue
	for(int i=0;i<10;++i)
		testq.push(i);
	testq2=testq;
	//Establish it is working
	cout<<testq.top()<<endl;
	testq.pop();
	cout<<testq.top()<<endl;
	testq.pop();
	//Clear it and prove that it worked
	clearpq(testq);
	cout<<testq.size()<<endl;
    //Use the second clearing function
	cout<<testq2.size()<<endl;
	clearpq2(testq2);
	cout<<testq2.size()<<endl;
}