priority queue clear method

Here's a clean and simple method to clear any priority_queue (and queue, and most other containers as well):

template <class Q>
void clearQueue(Q & q) {
    q = Q();
}

Since it's a template, you don't have to remember all the template parameters.

Example:

std::priority_queue<MyType> simpleQueue;
std::priority_queue<MyType, std::deque<MyType>, MyHashFunction> customQueue;

// ... later ...

clearQueue(customQueue);
clearQueue(simpleQueue);

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

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;
}

Tags:

C++

Stl