Removing an entry with erase
Entries sometimes have to go: a shop stops selling an item, or a player leaves a game. For an unordered_map, call erase with the key. The key and its value are removed together, and the size drops by 1.
unordered_map<string, int> animals;
animals["cat"] = 4;
animals["rabbit"] = 1;
animals.erase("rabbit");
cout << animals.size() << endl; // 1
After the erase, animals.count("rabbit") is 0, so the key is really gone.
What erase returns
When you pass a key, erase returns how many entries it removed: 1 if the key was there, 0 if it was not. A missing key is not an error. Nothing is removed, and the program goes on. Calling erase("rabbit") a second time returns 0.
You rarely need that number, but it can serve as a quick check that something was deleted.
Trap: checking with []
After you delete a key, do not check for it with animals["rabbit"]. The square brackets add a missing key back, with the value 0. The check would seem to say "zero rabbits", but the map would now hold a "rabbit" key again, and its size would be higher by 1. Use count instead, which only looks and never changes the map.
The exercise: the last rabbit
A pet shop keeps what it has for sale in animals: 4 cats, 2 dogs and 1 rabbit. Each key is a kind of animal and each value is how many the shop has. The code prints the size, which is 3. Then the last rabbit goes home with a family, so the task is:
- Delete the key
"rabbit"withanimals.erase("rabbit"). - Print
animals.size()again. One key is gone, so it is 2.
The code at the bottom then checks with count whether any rabbits are left. Because the key is deleted, it prints No rabbits left.
unordered_map<string, int> animals;
animals["cat"] = 4;
animals["dog"] = 2;
animals["rabbit"] = 1;
cout << animals.size() << endl;
animals.erase("rabbit");
cout << animals.size() << endl;
if (animals.count("rabbit") > 0) {
cout << "We still have rabbits" << endl;
} else {
cout << "No rabbits left" << endl;
}
The output is:
3
2
No rabbits left
Setting the rabbit count to 0 would not do the same job. animals["rabbit"] = 0 keeps the key, so count("rabbit") would stay 1 and the size would stay 3. To make a key disappear, you must erase it.
Order of the steps
The exercise prints the size before and after on purpose. Printing 3 and then 2 proves the entry was removed, not only hidden. If you move the erase above the first print, the output starts at 2 and the first line is wrong. Read the starter code to see where the blank space is, and put the new lines there, between the first print and the final check.
Key takeaways
m.erase(key)removes the key and its value, and shrinks the size by 1.- It returns 1 or 0, and a missing key is not an error.
- Setting a value to 0 is not deleting.
- Check for a key with
count, never with[], which adds it back.
