8.2 — Going through a list

📘 Chapter 8⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

The range-based for loop#

The easiest way to visit every item:

C++
std::vector<int> scores { 90, 72, 85 }; for (int s : scores){    std::cout << s << ' ';}
Output
90 72 85

Read it as: "for each s in scores".

Changing items in a loop#

Add & to work on the real items, not copies (more about & in 9.2 — References: another name for the same box):

C++
for (int& s : scores){    s += 5;   // everyone gets 5 bonus points}

Avoid copies of big things#

For strings or other big items, use const auto&. It's fast and safe:

C++
std::vector<std::string> names { "Ana", "Ben", "Cleo" };for (const auto& name : names){    std::cout << "Hi " << name << '\n';}
auto

auto tells C++ "work out the type for me". Here it becomes std::string.

When you need the index#

Use a normal for loop:

C++
for (std::size_t i { 0 }; i < names.size(); ++i){    std::cout << i + 1 << ". " << names[i] << '\n';}
Output
1. Ana2. Ben3. Cleo

Example: average score#

C++
std::vector<double> scores { 90, 72, 85, 64 };double total { 0.0 };for (double s : scores){    total += s;}std::cout << "Average: " << total / scores.size() << '\n';
Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.