C++ map count() Function
Example
Check if the keys "John" and "Jenny" exist in a map:
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.
A 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 <map> header file.
Tip: Use find() if you also want to get the element.
Syntax
map.count(keyType key)
keyType is the type of the keys in the map, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| key | Required. The key to look for. |
Technical Details
| Returns: | The number of elements with the given key: 1 or 0. |
|---|
Related Pages
Read more about maps in our Maps Tutorial.