C++ Deque Iterators

ww‮ditfigi.w‬ea.com

In C++, you can iterate over a deque using iterators. A deque provides bidirectional iterators that allow you to traverse the elements of the deque in both directions.

Here's an example of how to use iterators to iterate over a deque:

#include <iostream>
#include <deque>

int main() {
  std::deque<int> d {1, 2, 3, 4, 5};
  
  // Iterate over the deque using a for loop and an iterator
  std::cout << "Using an iterator: ";
  for (auto it = d.begin(); it != d.end(); ++it) {
    std::cout << *it << " ";
  }
  std::cout << std::endl;
  
  // Iterate over the deque using a ranged for loop and a const reference
  std::cout << "Using a const reference: ";
  for (const auto& x : d) {
    std::cout << x << " ";
  }
  std::cout << std::endl;
  
  return 0;
}

In this example, we create a deque d with five elements, and then we use an iterator in a for loop to print the values of all the elements in the deque. We then use a ranged for loop with a const reference to do the same thing.

The output of this program is:

Using an iterator: 1 2 3 4 5 
Using a const reference: 1 2 3 4 5

As you can see, we have successfully used iterators to iterate over the deque. Note that we can also use rbegin() and rend() methods to iterate over the deque in reverse order.