How to use std : : deque In C++
In above method extra copy queue is required to first copy all elements of queue which is not space efficient method. By using std : : dequeue we can iterate with efficient space which provides all the standard operations of std: :queue. We can traverse on dequeue using for range based for loop.
We can use dequeue: :cbegin() and dequeue: :cend() to print dequeue in forward direction and dequeue: :crbegin() and dequeue: :crend() to print dequeue in backward direction.
Example:
C++
// C++ program to iterate a STL Queue // using std : : dequeue #include <iostream> #include <queue> #include <algorithm> using namespace std; int main() { deque< int > dq; dq.push_back(1); dq.push_back(2); dq.push_back(3); dq.push_back(4); dq.push_back(5); cout << "Printing dequeue in forward direction : \n" ; for ( auto it = dq.cbegin();it!=dq.cend();it++) { cout << *it << " " ; } cout << "\n" ; cout << "Printing dequeue in reverse direction : \n" ; for ( auto it = dq.crbegin();it!=dq.crend();it++) { cout << *it << " " ; } return 0; } |
Printing dequeue in forward direction : 1 2 3 4 5 Printing dequeue in reverse direction : 5 4 3 2 1
Time complexity: O(n) // n is the size of the queue.
Auxiliary space: O(n).
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