HOWTO · C++

How to Iterate Through a Vector in C++

Learn four ways to traverse a C++ vector: indexed loops, range-based loops, iterators, and std::for_each.

On this page

For a straightforward visit to every element in a std::vector, use a range-based for loop. Choose an indexed loop when the position matters, iterators when an algorithm needs an iterator range, or std::for_each when you want to apply a callable to each element. The examples below target C++14.

Use an indexed for loop to traverse a vector

An indexed loop gives you both the element and its position. The three clauses in its header are separated by semicolons: initialize the index, continue while it is less than size(), then increment it. This complete C++14 example illustrates the pattern; no execution result is claimed here.

#include <cstddef>
#include <iostream>
#include <vector>

int main() {
    const std::vector<int> values = {45, 54, 87, 78};

    for (std::size_t i = 0; i < values.size(); ++i) {
        std::cout << values[i] << ' ';
    }
    std::cout << '\n';
}

This example declares values as const, so it is read-only: use values[i] to inspect the element at an index, but not to change it. To update a selected position, declare the vector as mutable (for example, std::vector<int> values = {45, 54, 87, 78};) and assign to values[i] inside the loop. The condition i < values.size() keeps each index within the vector’s valid element positions. Indexed access is useful when you need an element’s position, such as pairing values with another sequence or updating a selected slot. If the task only reads or changes each value in turn, a range-based loop is usually simpler because it avoids maintaining an index.

size() reports the number of elements, while indexing starts at zero, so the last element is at size() - 1 when the vector has elements. The strict less-than condition is what prevents the loop from trying that count as an index. Keep the index type compatible with the vector’s size type when adapting the loop to other element types.

Use a range-based for loop

A range-based for loop visits each element without maintaining an index. Use const auto& to read elements without copying them; use auto& when the loop should update the original values. This C++14 example illustrates both forms; no execution result is claimed here.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> values = {45, 54, 87, 78};

    for (const auto& value : values) {
        std::cout << value << ' ';
    }
    std::cout << '\n';

    for (auto& value : values) {
        value += 1;
    }
}

The first loop binds each value as a read-only reference. The second binds a mutable reference, so assignments affect the corresponding elements in values. If you only need to inspect values, prefer the const form to make that intent clear.

Traverse a vector with iterators

Use an iterator when an interface accepts a pair of positions or when you need to advance through a container explicitly. Start at begin() and continue until end(). The end() iterator marks the position just after the last element; dereference the current iterator, never end() itself. This C++14 example illustrates the traversal; no execution result is claimed here.

#include <iostream>
#include <vector>

int main() {
    const std::vector<int> values = {45, 54, 87, 78};

    for (std::vector<int>::const_iterator it = values.begin();
         it != values.end(); ++it) {
        std::cout << *it << ' ';
    }
    std::cout << '\n';
}

The != comparison expresses the usual half-open iterator range [begin(), end()). A const_iterator allows reading each element while preventing changes through that iterator.

The same pair of iterators can be passed to standard algorithms, which is why explicit iterator traversal is useful when code already works with iterator ranges. For a read-only vector, begin() and end() provide const iterators; for a mutable vector, they provide iterators that can update elements when dereferenced.

Apply an operation with std::for_each

std::for_each from <algorithm> applies a callable to every element in the half-open range from begin() up to, but not including, end(). A lambda keeps the operation next to the traversal. This C++14 example illustrates adding ten to each value through a mutable reference; no execution result is claimed here.

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> values = {1, 2, 3};

    std::for_each(values.begin(), values.end(), [](int& value) {
        value += 10;
    });

    for (const auto& value : values) {
        std::cout << value << ' ';
    }
    std::cout << '\n';
}

Use a const int& lambda parameter when the callable only reads elements. For a simple visit, a range-based loop is usually easier to scan; choose std::for_each when passing the operation as a callable fits the surrounding code. All four approaches traverse the same vector elements, with different access to positions and operations.