Code Snippets
/

Range-Based For Loop Patterns

Range-Based For Loop Patterns

The range-based `for` loop (C++11) is the idiomatic way to iterate any container or any type with `begin()` / `end()`. This snippet covers the three reference flavours (by value, by const reference, by mutable reference), iterating over arrays and `std::initializer_list`, and how to also access the index when you need it. Get the reference forms right and you avoid both copies and accidental mutations.

C++
Easy
3 snippets
cpp-range-based-for
cpp-stl
iteration-patterns

550 views

2

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> words = {"alpha", "beta", "gamma"};

    // BAD: by value copies each std::string into the loop variable.
    // for (std::string w : words) std::cout << w << "\n";

    // GOOD: const reference reads without copying and prevents mutation.
    for (const std::string& w : words) std::cout << w << "\n";

    // For trivially copyable types like int, by value is fine.
    std::vector<int> nums = {1, 2, 3};
    for (int n : nums) std::cout << n << " ";
    std::cout << "\n";
    return 0;
}

Take by const T& for any non-trivial element type to skip the copy and document read-only intent. For built-in types like int, double, or pointers, by value is just as fast and reads cleaner. The classic mistake is for (auto x : v) over a vector<string>: it silently copies every element, which can dominate the loop's runtime on a large vector of strings. Make auto a default but pair it with & (for (const auto& x : v)) for the same reason.