Creating copy of given std : : queue
If we want to iterate on std: :queue then we can create a temporary copyqueue and we can copy all elements of queue into copyqueue then we can easily traverse on copyqueue and find the elements of queue using std: :front() function and delete element from queue using std: :pop function.
Example:
C++
// C++ program to iterate a STL Queue // by Creating copy of given // std : : queue #include <iostream> #include <queue> using namespace std; int main() { // creating std :: queue in c++ queue< int > q; // pushing elements using std :: push() q.push(1); q.push(2); q.push(3); q.push(4); q.push(5); // creating copy queue to // copy all elements of queue queue< int > copy_queue = q; cout << "Elements of queue are :\n" ; // traversing on copyqueue // until it becomes empty while (!copy_queue.empty()) { // printing front element of queue cout << copy_queue.front() << " " ; // deleting element from // queue using std :: pop() // function copy_queue.pop(); } return 0; } |
Elements of queue are : 1 2 3 4 5
How to Iterate a STL Queue in C++?
A Queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO).
Syntax:
queue<datatype> queuename;
Datatype: Queue can take any data type depending on the values, e.g. int, char, float, etc.
The std: :queue container does not provide std: :begin function and std: :end function from which we can iterate on the queue using iterator. In simple words std: :queue is not iterated over.
There are 3 methods from which we can iterate on queue i.e.
- Using standard std: :front and std: :pop method
- Creating copy of given std: :queue
- Using std: :deque