Range-based for Loop in C++
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().
No indexes, no bounds
for (int x : v) runs once per element of v — bounds and increments are handled invisibly and cannot be wrong.
auto& to modify
for (auto& x : v) { x *= 2; } doubles the actual stored elements; without the &, you would double throwaway copies.
const auto& to read cheaply
for (const auto& s : names) reads each string with no copies and a compiler guarantee against mutation.
Never mutate the container itself
Adding or removing elements mid-loop invalidates the hidden iterators — collect changes and apply them after.
#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;}Visits each of the n elements once; references add no storage.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.