[c++] std::queue iteration

I need to iterate over std::queue. www.cplusplus.com 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?

This question is related to c++ queue iteration c++-standard-library

The answer is


In short: No.

There is a hack, use vector as underlaid container, so queue::front will return valid reference, convert it to pointer an iterate until <= queue::back


I use something like this. Not very sophisticated but should work.

    queue<int> tem; 

    while(!q1.empty()) // q1 is your initial queue. 
    {
        int u = q1.front(); 

        // do what you need to do with this value.  

        q1.pop(); 
        tem.push(u); 
    }


    while(!tem.empty())
    {
        int u = tem.front(); 
        tem.pop(); 
        q1.push(u); // putting it back in our original queue. 
    }

It will work because when you pop something from q1, and push it into tem, it becomes the first element of tem. So, in the end tem becomes a replica of q1.


Why not just make a copy of the queue that you want to iterate over, and remove items one at a time, printing them as you go? If you want to do more with the elements as you iterate, then a queue is the wrong data structure.


while Alexey Kukanov's answer may be more efficient, you can also iterate through a queue in a very natural manner, by popping each element from the front of the queue, then pushing it to the back:

#include <iostream>
#include <queue>

using namespace std;

int main() {
    //populate queue
    queue<int> q;
    for (int i = 0; i < 10; ++i) q.push(i);

    // iterate through queue
    for (size_t i = 0; i < q.size(); ++i) {
        int elem = std::move(q.front());
        q.pop();
        elem *= elem;
        q.push(std::move(elem));
    }

    //print queue
    while (!q.empty()) {
        cout << q.front() << ' ';
        q.pop();
    }
}

output:

0 1 4 9 16 25 36 49 64 81 

If you need to iterate a queue ... queue isn't the container you need.
Why did you pick a queue?
Why don't you take a container that you can iterate over?


1.if you pick a queue then you say you want to wrap a container into a 'queue' interface: - front - back - push - pop - ...

if you also want to iterate, a queue has an incorrect interface. A queue is an adaptor that provides a restricted subset of the original container

2.The definition of a queue is a FIFO and by definition a FIFO is not iterable


One indirect solution can be to use std::deque instead. It supports all operations of queue and you can iterate over it just by using for(auto& x:qu). It's much more efficient than using a temporary copy of queue for iteration.


std::queue is a container adaptor, and you can specify the container used (it defaults to use a deque). If you need functionality beyond that in the adaptor then just use a deque or another container directly.


you can save the original queue to a temporary queue. Then you simply do your normal pop on the temporary queue to go through the original one, for example:

queue tmp_q = original_q; //copy the original queue to the temporary queue

while (!tmp_q.empty())
{
    q_element = tmp_q.front();
    std::cout << q_element <<"\n";
    tmp_q.pop();
} 

At the end, the tmp_q will be empty but the original queue is untouched.


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>
{
public:
    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)
        int_queue.push(i);
    for(auto it=int_queue.begin(); it!=int_queue.end();++it)
        std::cout << *it << "\n";
    return 0;
}

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to queue

Difference between "enqueue" and "dequeue" C++11 thread-safe queue Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue How to clone object in C++ ? Or Is there another solution? How to check queue length in Python what is the basic difference between stack and queue? FIFO based Queue implementations? Deleting queues in RabbitMQ "Cannot instantiate the type..." Size-limited queue that holds last N elements in Java

Examples related to iteration

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? How to loop over grouped Pandas dataframe? How to iterate through a list of dictionaries in Jinja template? How to iterate through an ArrayList of Objects of ArrayList of Objects? Ways to iterate over a list in Java Python list iterator behavior and next(iterator) How to loop through an array containing objects and access their properties recursion versus iteration What is the perfect counterpart in Python for "while not EOF" How to iterate over a JavaScript object?

Examples related to c++-standard-library

What does string::npos mean in this code? Deleting elements from std::set while iterating std::string formatting like sprintf std::queue iteration How to convert std::string to lower case?