std::queue iteration


I need to iterate over std::queue. says:

By default, if no container class is specified for a particular queue class, the standard container class template deque is used.

So can I somehow get to the queue's underlying deque and iterate over it?

4/25/2016 12:41:48 AM

Accepted Answer

If you need to iterate over a queue then you need something more than a queue. The point of the standard container adapters is to provide a minimal interface. If you need to do iteration as well, why not just use a deque (or list) instead?

8/11/2009 8:49:44 AM

While I agree with others that direct use of an iterable container is a preferred solution, I want to point out that the C++ standard guarantees enough support for a do-it-yourself solution in case you want it for whatever reason.

Namely, you can inherit from std::queue and use its protected member Container c; to access begin() and end() of the underlying container (provided that such methods exist there). Here is an example that works in VS 2010 and tested with ideone:

#include <queue>
#include <deque>
#include <iostream>

template<typename T, typename Container=std::deque<T> >
class iterable_queue : public std::queue<T,Container>
    typedef typename Container::iterator iterator;
    typedef typename Container::const_iterator const_iterator;

    iterator begin() { return this->c.begin(); }
    iterator end() { return this->c.end(); }
    const_iterator begin() const { return this->c.begin(); }
    const_iterator end() const { return this->c.end(); }

int main() {
    iterable_queue<int> int_queue;
    for(int i=0; i<10; ++i)
    for(auto it=int_queue.begin(); it!=int_queue.end();++it)
        std::cout << *it << "\n";
    return 0;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow