Start learning free

LESSON 127 OF 667 · DICTIONARIES

Deleting a Key from a C++ unordered_map

Lesson Read the full explanation

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

    C++ · DICTIONARIES

    Deleting Dictionary Keys in C++, explained

    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:

    1. Delete the key "rabbit" with animals.erase("rabbit").
    2. 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.
    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free