DevAcademia lesson/C++ Basics
Range-based For Loop
Topic progressTopic 48 of 109 - 44% complete
~8 min lesson22 learning blocks5 code examples1 checks/interactions
Lesson outline
Modern Iteration
Introduced in C++11, the range-based for loop automatically iterates through all elements in a range without explicit counter management.
Works with raw arrays, std::array, STL containers, initializer lists, and user-defined types that are range-like (i.e., have begin/end member functions or free begin/end found by ADL).
Basic Usage
Modification Example
Maps & Structured Bindings (C++17)
When iterating key - value containers, structured bindings make code clearer.
Initializer Lists & Arrays
You can iterate braced lists and raw arrays directly.
C++20: Init-statement in Range-for
Since C++20, you can add an init-statement before the range declaration.
Supported Containers
- Raw (C-style) arrays and std::array
- STL containers (vector, string, list, deque, set, map, unordered_*)
- Initializer lists (e.g., {1,2,3})
- User-defined types with begin()/end() or free begin/end (ADL)
- C++20 ranges/views that expose begin/end
Pitfalls & Tips
- Iteration by value (
auto x) copies each element; preferconst auto&for read-only,auto&for mutation. - Modifying the container (insert/erase) during iteration can invalidate references/iterators for some containers (e.g., vector, string).
- If you need the index, use a traditional index-based loop or maintain a separate counter.
- Order of iteration depends on the container (e.g.,
mapis ordered by key;unordered_maphas no defined order). - With proxy-reference containers like
std::vector<bool>, useauto&to actually modify elements.
Was this topic clear?