How to use standard std : : front and std : : pop method In C++
We can iterate on queue using std: :front which will return the front element of the queue and std: :pop which will remove the front element of the queue. But, after iterating on the queue with this method queue will vanish as we are deleting elements of the queue as we iterate over it.
Example:
C++
// C++ program to iterate a STL Queue // using standard std : : front and // std : : pop method #include <iostream> #include <queue> using namespace std; int main() { // creating std :: queue in c++ queue< int > q; // inserting elements in queue // using std :: push method q.push(1); q.push(2); q.push(3); q.push(4); q.push(5); cout << "Elements of queue are : \n" ; while (!q.empty()) { // getting front element of queue cout << q.front() << " " ; // removing front element of queue q.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