C++ Snippet

Range-Based For Loop Patterns

Difficulty: Easy

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.

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

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.