Start learning free

LESSON 127 OF 667 · DICTIONARIES

Deleting a Key in C++

Lesson

TL ; DR:

An unordered_map's erase method takes a key. It deletes that key and its value.


unordered_map<string, int> toys;
toys["ball"] = 3;
toys["kite"] = 1;

toys.erase("kite");

cout << toys.size() << endl;   // 1


Full lesson:

Sometimes an entry has to go. A shop stops selling an item. A player leaves the game.

Call erase on the map with the key. The key and its value go away together.

The size drops by 1. The key is gone, so toys.count("kite") is now 0.

erase returns how many entries it deleted. That's 1, or 0 for a missing key. A missing key is no error.

Watch out: don't check with toys["kite"] afterwards. The [] adds the key back, with the value 0! Use count to check.


Your task

A pet shop counts what it has for sale in animals. Each key is a kind of animal. Its value is how many the shop has.

The last rabbit just went home with a family. Delete the key "rabbit" from animals.

Then print animals.size() again. The code at the bottom checks if any rabbits are left.

Expected output:

3
2
No rabbits left
STEP 1 OF 2
    Ctrl + Enter to check