Start learning free

LESSON 126 OF 667 · DICTIONARIES

Reading a Key That May Be Missing in C++

Lesson

TL ; DR:

Start with the default. Then an if with count replaces it with the value, when the key is there.


unordered_map<string, int> points = {{"Ana", 7}};

int score = 0;
if (points.count("Ben") > 0) {
    score = points["Ben"];
}
cout << score << endl;   // 0


Full lesson:

A missing key often means "none yet". A player with no points yet has 0 points.

points["Ben"] gives 0 too, but it does one more thing. On a missing key, [] adds the key, with 0.

So reading with [] changes the map. points.size() would go from 1 to 2.

The if reads points["Ben"] only when the key is already there. So points keeps one key.

With "Ana", the same code gives 7.


Your task

stock counts the fruit in a shop. The code reads and prints the pears.

There are no plums yet. Declare an int named plums at 0. Then use an if with count to read stock["plums"] when the key is there.

Then print the plums line, the same way as the pears line.

Expected output:

We have 2 pears
We have 0 plums
STEP 1 OF 3
    Ctrl + Enter to check