This post will discuss how to iterate over a deque in C++ in the forward and backward directions.

A deque (or Double-ended queue) is a sequence container that can be expanded or contracted on both ends and usually implemented as a dynamic array by most libraries.

1. Using array indices

Since deque is implemented as a dynamic array, we can easily get the element present at any index using the [] operator. The idea is to iterate a queue using a simple for-loop, and for every index, we print the corresponding element.

Download  Run Code

Output:

1 2 3 4 5
5 4 3 2 1

2. Using iterators

We can use deque::cbegin and deque::cend to iterate deque in forward direction and deque::crbegin and deque::crend to iterate deque in backward direction.

Please note that the use of const_iterators is recommended since the iteration is read-only.

Download  Run Code

Output:

1 2 3 4 5
5 4 3 2 1

3. Using STL std::copy function

Another good alternative is to use the std::copy for copying deque contents to the output stream using the output iterator.

Download  Run Code

Output:

1 2 3 4 5
5 4 3 2 1

 
With C++17, we can use std::copy with std::experimental::ostream_joiner defined in <experimental/iterator> header.

Run Code

Output (g++ -std=c++17):

1 2 3 4 5

4. Using std::for_each algorithm

We can also use the STL algorithm std::for_each, which applies a specified function to every deque element. We can also replace the function call with a lambda in C++11, which is another way of defining an inline, anonymous functor.

Download  Run Code

Output:

1 2 3 4 5
5 4 3 2 1

5. Overloading operator>> and operator<<

The idea is to overload the operator>> to print std::deque in the output stream in the forward direction. Similarly, we can overload the operator<< to print std::deque in the backward direction, as shown below:

Download  Run Code

Output:

1 2 3 4 5
5 4 3 2 1

6. Using range-based for-loop

Finally, we can use a range-based for-loop in C++11 to print the deque contents in the forward direction, but it doesn’t support backward iteration.

Download  Run Code

Output:

1 2 3 4 5

That’s all about iterating over a deque in C++.