Range-Based for Loop with Containers
Iterate cleanly over containers with the C++11 range-based for syntax.
The Modern Loop
C++11 introduced the range-based for loop — iterate any container without explicit indices or iterators. Cleaner and harder to get wrong.
std::vector<int> v = {1, 2, 3, 4, 5};
for (int x : v) {
std::cout << x << " ";
}By Value
The example above copies each element into x. Fine for cheap types like int; expensive for large objects.
All lessons in this course
- Branching: if-else, ternary, switch-case
- Loop Patterns: for, while, do-while
- Range-Based for Loop with Containers
- Early Returns break continue and goto