Iterate over a deque in C++ (Forward and Backward directions)

In this post, we will discuss how to iterate over a deque in C++ in forward and backward directions.


 

A deque (or Double ended queue) is sequence container that can be expanded or contracted on both its ends. Is 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 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

Another good alternative is to use 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 STL algorithm std::for_each, which applies a specified function to every element in deque. We can also replace the function call by 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 backward direction as shown below:

 

Download   Run Code

Output:

1 2 3 4 5
5 4 3 2 1

 

6. Range based for loop

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

 

Download   Run Code

Output:

1 2 3 4 5

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Categories

Leave a Reply

Notify of
avatar
wpDiscuz