This lesson exists because the STL's core design idea — algorithms that work on ANY container — needs a common currency, and iterators are that currency. Learn the loop styles here and unit 9's entire algorithm library opens up with no new syntax.
Range-based for: Python's for-in, in C++
Since C++11, iterating a container looks like this:
std::vector<int> v = {1, 2, 3}; for (int x : v) { // x is a COPY of each element std::cout << x; } for (int& x : v) { // x is a REFERENCE: modify the real elements x *= 2; } for (const std::string& s : words) { // big elements: const& avoids copies std::cout << s; }
The value/reference distinction is lesson 4-2 all over again, applied per element. Copies for cheap reads, & to mutate, const& for big read-only elements.
auto
auto lets the compiler deduce a variable's type from its initializer. for (auto& x : v) adapts if v's element type changes. Use it where the type is obvious from context, write the type out where it teaches the reader.
Iterators, briefly
Range-for is sugar over iterators: pointer-like objects where v.begin() points at the first element and v.end() points one past the last. The pointer walk you wrote in lesson 5-2 is exactly this shape, and every STL algorithm in unit 9 takes a begin/end pair.
Code exercise · cpp
Run this. The first loop fails to change v because x is a copy. The second, with &, really modifies the elements.
Code exercise · cpp
Run the explicit iterator loop — this is exactly what the range-for above compiles down to. Note `auto` hiding the real type, which is the mouthful std::vector<std::string>::iterator.
Quiz
You want to lowercase every string in a std::vector<std::string> in place. Which loop header is right?
Code exercise · cpp
Your turn. Read 5 integers into a vector. Use a reference range-for to square each element in place, then a plain range-for to sum them, and print the sum. Input is `1 2 3 4 5`, expected output `sum of squares: 55`.