1. Problem It Solves
C++11 containers own their elements and expose a common iteration model, while range-for and std::begin/end work with both containers and built-in arrays. It makes an important constraint visible instead of leaving readers to guess. This lesson keeps only the C++11 core that fits one focused day.
2. Prerequisites
The ideas from Day 9, plus basic variables, functions, and output already introduced.
3. Core Idea
Mental model: C++11 containers own their elements and expose a common iteration model, while range-for and std::begin/end work with both containers and built-in arrays. Identify the relevant value or state, who owns it, and whether the rule acts during compilation or execution.
4. Minimal Syntax
std::array<int, 3> a{{1,2,3}}; for (int x : a) { }5. How It Works
The example creates a tiny fixed state with no keyboard input.
C++11 or the standard-library contract applies today's rule.
The program prints the important result so it can be checked against the source.
6. Common Mistakes
Using an index outside the valid range is undefined behavior with unchecked access; modifying a vector during iteration can also invalidate traversal state.
7. When to Use It
Use it when you need fixed-size or growable owned sequences with simple iteration.
Avoid it when it hides ownership, lifetime, type, ordering, or cost.
8. Simple Example
The program sums a std::array and a std::vector with range-for, then uses std::begin/end on a built-in array. The .cpp keeps the data fixed and avoids unrelated abstraction.
Complete sample code
Source file
cpp11/10_array_vector_range_for_begin_end/main.cpp
#include <array>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::array<int, 3> fixed{{1, 2, 3}};
std::vector<int> growing{4, 5, 6};
int raw[]{7, 8};
int sum = 0;
for (int value : fixed) {
sum += value;
}
for (int value : growing) {
sum += value;
}
std::cout << "sum=" << sum << '\n';
std::cout << "raw_size=" << std::end(raw) - std::begin(raw) << '\n';
}
9. Key Takeaways
The feature is part of the C++11 scope used in this course.
Understand its lifetime, ownership, type, and ordering consequences.
Compile with warnings and prefer the smallest form that makes the rule obvious.
10. Self-Check Questions
Easy — Can C++11 range-based for iterate over
std::array,std::vector, and a built-in array? What range dostd::beginandstd::enddescribe?Medium — Read the small example described above. What value or state should it print, and which rule produces that result?
Hard — Find and explain the subtle bug in this situation: Using an index outside the valid range is undefined behavior with unchecked access; modifying a vector during iteration can also invalidate traversal state. What is the smallest C++11-safe correction?