This post will discuss how to iterate through a queue in C++.

1. Using std::queue

The std::queue container does not contain the std::begin function and there isn’t any overload of std::begin which accepts a std::queue. In other words, std::queue is not meant to be iterated over.

 
If you need to iterate over a std::queue, you can create a copy of it and remove items from the copy, one at a time, using the standard pop function after processing it. This way the original queue remains untouched, but its copy becomes empty.

Download  Run Code

Output:

1
2
3
4

2. Using std::deque

The above solution creates a temporary copy of the queue just for iteration, which is not efficient. Consider using the std::deque instead, which supports all standard operations of a std::queue, and can be iterated over using the range-based for-loop. We can insert and remove elements at the end and the front of a deque using the push_back and pop_front operations.

Download  Run Code

Output:

1
2
3
4

That’s all about iterating through a queue in C++.