Learn C++
#include "controlflow/range_for.hpp"

Range-based for Loop in C++

//concept

The range-based for loop (C++11) visits every element without indexes: for (int x : v) reads each value, for (auto& x : v) modifies in place. It eliminates off-by-one errors entirely — there is no bound to get wrong — and reads as plain intent: do this to each element.

The reference choice matters: plain auto copies each element (wasteful for strings, and writes vanish), const auto& reads cheaply, auto& writes back. It works on arrays, vectors, strings, maps, and anything with begin()/end().

//how it works
1

No indexes, no bounds

for (int x : v) runs once per element of v — bounds and increments are handled invisibly and cannot be wrong.

2

auto& to modify

for (auto& x : v) { x *= 2; } doubles the actual stored elements; without the &, you would double throwaway copies.

3

const auto& to read cheaply

for (const auto& s : names) reads each string with no copies and a compiler guarantee against mutation.

4

Never mutate the container itself

Adding or removing elements mid-loop invalidates the hidden iterators — collect changes and apply them after.

//example
#include <iostream>
#include <vector>
 
int main() {
std::vector<int> v{1, 2, 3};
for (auto& x : v) {
x *= 10;
}
for (int x : v) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
Output
10 20 30
1The first loop binds each element by reference and multiplies the stored value by 10.
2The second loop copies each (now 10, 20, 30) for printing — copies are fine when only reading.
3One line shows all three transformed values in order.
//complexity
time O(n)
space O(1)

Visits each of the n elements once; references add no storage.

//use cases
Printing or summing every element of a vector, array, or string
Transforming containers in place with auto&
Iterating maps as for (auto& [k, v] : m) with structured bindings
Replacing every hand-rolled index loop that never needed the index

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.