-->

C++ - Vectors Part 3: Iterating Over Vectors

C++ vectors can be traversed using loops or iterators.

Examples and Explanation

Using a For Loop

for (size_t i = 0; i < vec.size(); i++) {

    std::cout << vec[i] << " ";

}

Explanation: A traditional loop provides indexed access to elements.

Using a Range-Based For Loop

for (int val : vec) {

    std::cout << val << " ";

}

Explanation: Range-based loops simplify traversal by directly accessing elements.

Using Iterators

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

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

}

Explanation: Iterators provide a flexible way to traverse vectors, allowing element modification and advanced operations.