Start learning free

LESSON 221 OF 667 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Looping Over a Dictionary in C++

Lesson

TL ; DR:

A range-based for loop over an unordered_map visits every entry. The [fruit, amount] part splits each one into its key and its value.


unordered_map<string, int> stock;
stock["apples"] = 5;
stock["pears"] = 2;

for (auto& [fruit, amount] : stock) {
    cout << fruit << " " << amount << endl;
}

// pears 2
// apples 5   (in any order)


Full lesson:

A loop can visit every entry of a map, one at a time. The loop body runs once per key.

Each entry of the map is a pair of a key and its value. [fruit, amount] gives both parts a name.

auto lets C++ work out the types. The & visits each entry where it is, without a copy.

Older code writes entry.first for the key and entry.second for the value. It's the same pair.

The order: an unordered_map has no fixed order. That's what "unordered" means. A total or a count comes out the same in any order. Those are safe answers.

Watch out: don't add keys inside the loop. Even reading stock[key] with a new key adds that key.


Your task

A game keeps each player's points in scores. The variables total and count start at 0.

Loop over scores. Add every player's points to total. Count the players with 10 points or more in count.

The code at the bottom prints both.

Expected output:

43
2
STEP 1 OF 3
    Ctrl + Enter to check