Start learning free

LESSON 125 OF 667 · DICTIONARIES

Checking for a Key in C++

Lesson

TL ; DR:

Call m.count(key) to ask whether an unordered_map has a key. It returns 1 when the key is there and 0 when it isn't.


unordered_map<string, string> capitals = {{"France", "Paris"}, {"Japan", "Tokyo"}};

if (capitals.count("Japan") > 0) {
    cout << capitals["Japan"] << endl;   // Tokyo
}

if (capitals.count("Spain") == 0) {
    cout << "No Spain" << endl;          // No Spain
}


Full lesson:

A map has each key at most once. So count can only be 1 or 0.

capitals.count("Spain") > 0 is true when "Spain" is a key. == 0 asks the opposite.

Don't check with capitals["Spain"]. On a missing key, [] adds the key, with an empty value.

Newer C++ also has a contains method. This course uses C++17, which doesn't have it. So use count.

A value is not a key

count looks only at the keys. capitals.count("Paris") is 0, because "Paris" is a value.

A key must match exactly, upper and lower case too. capitals.count("japan") is 0.


Your task

In pets, each key is a pet's name, and its value is the pet's kind.

First, check whether "Tom" is a key of pets. If it is, print Tom is a followed by Tom's kind.

Then check that "cat" is not a key, with count. If so, print cat is not a key.

"cat" is in pets, but only as a value. It is Tom's kind.

Expected output:

Tom is a cat
cat is not a key
STEP 1 OF 2
    Ctrl + Enter to check