Iterate through a queue in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <queue> int main() { std::queue<int> q; q.push(1); q.push(2); q.push(3); q.push(4); std::queue<int> q_copy = q; while (!q_copy.empty()) { int front = q_copy.front(); std::cout << front << std::endl; q_copy.pop(); } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <deque> int main() { std::deque<int> q; q.push_back(1); q.push_back(2); q.push_back(3); q.push_back(4); for(auto &i: q) { std::cout << i << std::endl; } return 0; } |
Output:
1
2
3
4
That’s all about iterating through a queue in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)