0
0
CppHow-ToBeginner · 3 min read

How to Iterate Over Vector in C++: Simple Examples and Tips

To iterate over a std::vector in C++, you can use a range-based for loop, traditional for loop with indices, or iterators. The range-based for loop is the simplest and most readable way to access each element directly.
📐

Syntax

Here are common ways to iterate over a std::vector:

  • Range-based for loop: loops directly over elements.
  • Index-based for loop: uses indices to access elements.
  • Iterator-based loop: uses vector iterators to traverse.
cpp
std::vector<int> vec = {1, 2, 3, 4, 5};

// Range-based for loop
for (int value : vec) {
    // use value
}

// Index-based for loop
for (size_t i = 0; i < vec.size(); ++i) {
    // use vec[i]
}

// Iterator-based loop
for (auto it = vec.begin(); it != vec.end(); ++it) {
    // use *it
}
💻

Example

This example shows how to print all elements of a vector using the range-based for loop.

cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {10, 20, 30, 40, 50};

    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}
Output
10 20 30 40 50
⚠️

Common Pitfalls

Common mistakes when iterating over vectors include:

  • Using an index beyond vec.size(), causing out-of-bounds errors.
  • Modifying the vector while iterating with iterators without care, which can invalidate iterators.
  • Using int for indices instead of size_t, which may cause warnings or errors on some systems.
cpp
/* Wrong: index goes out of bounds */
std::vector<int> v = {1, 2, 3};
for (size_t i = 0; i <= v.size(); ++i) { // <= causes out-of-bounds on last iteration
    std::cout << v[i] << " ";
}

/* Right: use < instead of <= */
for (size_t i = 0; i < v.size(); ++i) {
    std::cout << v[i] << " ";
}
📊

Quick Reference

Tips for iterating over vectors:

  • Use range-based for loops for simple and clear code.
  • Use iterators when you need to modify elements or use algorithms.
  • Always check vector size to avoid out-of-bounds errors.

Key Takeaways

Use range-based for loops for the simplest way to iterate over vectors.
Always ensure your loop indices stay within vector size to avoid errors.
Iterators provide flexible traversal but be careful when modifying the vector.
Prefer size_t type for indices to match vector size type.
Avoid modifying a vector while iterating unless you understand iterator invalidation.