Skip to content

How to iterate over a priority_queue?

An answer to this question on Stack Overflow.

Question

Can I traverse a standard priority_queue or standard queue in c++ with an iterator (like a vector)? I don't want to use pop because it cause my queue to be dequeued.

Thanks for any help

Answer

You can do it like this - bam! Notice that items are not necessarily in "sorted" order while they are in the queue, at least with regards to a straight-forward iteration of the container.

#include <queue>
#include <cstdlib>
#include <iostream>
using namespace std;
template <class T, class S, class C>
S& Container(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;
        }
    };
    return HackedQueue::Container(q);
}
int main()
{
    priority_queue<int> pq;
    vector<int> &tasks = Container(pq);
	cout<<"Putting numbers into the queue"<<endl;
	for(int i=0;i<20;i++){
		int temp=rand();
		cout<<temp<<endl;
		pq.push(temp);
	}
	cout<<endl<<"Reading numbers in the queue"<<endl;
	for(vector<int>::iterator i=tasks.begin();i!=tasks.end();i++)
		cout<<*i<<endl;
	cout<<endl<<"Taking numbers out of the queue"<<endl;
	while(!pq.empty()){
		int temp=pq.top();
		pq.pop();
		cout<<temp<<endl;
	}
    return 0;
}