Modern C++ • C++20 baseline
Loops and Range-Based for
Choose loops that make iteration boundaries and mutation clear.
Use a range-based for loop to visit each element when the index is not needed. Use an indexed loop when position is meaningful, and ensure the index type can represent the container size. An algorithm such as std::transform may express a transformation more clearly than a hand-written loop.
Key points
- Do not modify a container in ways that invalidate the active iterator or reference.
- Use const auto& when reading larger elements without copying.
Example
#include <iostream>
#include <vector>
int main() {
const std::vector<int> scores{82, 91, 76};
for (const int score : scores) {
std::cout << score << '\n';
}
}
What to expect
Prints each score on its own line.
Practice exercise
Calculate the average score. Handle the empty-vector case before dividing.
Key idea: Choose the loop form that communicates whether you need values, references, or indices.