C++ unordered_map count() Function
Example
Check if the keys "John" and "Jenny" exist in an unordered map:
unordered_map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
cout << people.count("John") << "\n";
cout << people.count("Jenny");
Definition and Usage
The count() function returns the number of elements with the given key.
An unordered map cannot have two elements with the same key, so the result is always 1 (the key exists) or 0 (the key does not exist). This makes count() an easy way to check if a key exists.
The count function is defined in the <unordered_map> header file.
Tip: Use find() if you also want to get the element.
Syntax
unordered_map.count(keyType key)
keyType is the type of the keys in the unordered map, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| key | Required. The key to search for. |
Technical Details
| Returns: | The number of elements with the given key: 1 or 0. |
|---|
Related Pages
Read more about unordered maps in our Unordered Map Tutorial.