Overusing index-based loops makes iteration longer, harder to read, and vulnerable to off-by-one errors. A range-based for loop focuses on each element instead of loop mechanics. section 2.6
Read the colon as “in”: each element is assigned to the loop variable in sequence. By default, that variable is a copy, so changes do not affect the container and class elements may be copied expensively. Prefer a const reference for read-only class elements, or a non-const reference when modification is required. section 2.6
Listing 2.11 Using index values to iterate over a container
template <typename T>
T sum(const std::vector<T>& values) {
T sum = (T)0;
for (int i = 0; i < values.size(); ++i) #1
sum += values[i];
return sum;
}
int main() {
std::vector<int> values;
for (int i = 0; i < 10; ++i)
values.push_back(10*i + i); #2
std::cout << sum(values) << '\n';
return 0;
}
Compare indexed traversal with a range-based sum function using const references. section 2.6

