This post will discuss how to determine if a key exists in a map in C++.

1. Using std::map::find

The standard way to use the std::map::find function that searches a map for a key and returns an iterator to it, or the std::map::end if the key is not present in the map. The following code example shows invocation for this function:

Download  Run Code

Output:

Key found

2. Using std::map::count

Another option is to use std::map::count to get the total number of elements in the map with a particular key. If a key is present in the map, the count would be exactly 1 since all keys in the map container are unique. If the key is not found, the count function returns zero.

Download  Run Code

Output:

Key found

3. Using std::map::contains

Another option to check whether a particular key exists in the map is using the std::map::contains member function. This function is available since C++20. It returns true if the map contains an element with a specific key, false otherwise.

Download Code

Output:

Key found

That’s all about determining if a key exists in a map in C++.