-->

C++ - C++ Deque Part 4: Iterating Over a Deque

Deques support three main types of iteration:

Range-based for loop

Iterator-based loop

Reverse iteration

Example 7: Iterating Using a For Loop

#include <iostream>

#include <deque>

int main() {

    std::deque<int> dq = {1, 2, 3, 4, 5};

    for (int num : dq) {

        std::cout << num << " ";

    }

    return 0;

}

Output:

1 2 3 4 5

Example 8: Iterating Using Iterators

#include <iostream>

#include <deque>

int main() {

    std::deque<int> dq = {1, 2, 3, 4, 5};

    for (auto it = dq.begin(); it != dq.end(); ++it) {

        std::cout << *it << " ";

    }

    return 0;

}

Output:

1 2 3 4 5