This post will discuss how to check if a given key exists in a map or not in C++.

1. Using unordered_map::find function

To check for the existence of a particular key in the map, the standard solution is to use the public member function find() of the ordered or the unordered map container, which returns an iterator to the key-value pair if the specified key is found, or iterator to the end of the container if the specified key is not found.

Download  Run Code

Output:

Key not found

2. Using unordered_map::count function

If we only want to know the presence of a key in the map container but doesn’t want an iterator to it, we can use the count() member function of the map container, which returns the value of 1 if the specified key is found, or 0 if the key is not found. Since all the keys in a map are distinct, count() internally uses find() function.

Download  Run Code

Output:

Key found

3. Using STL algorithms

There are many algorithms offered by the standard library like std::find_if, std::count_if, std::for_each, std::any_of, etc., which can be used to linearly searches the map container for a key.

std::find_if function

Download  Run Code

Output:

Key found

std::count_if function

Download  Run Code

Output:

Key not found

std::for_each function

Download  Run Code

Output:

Key found

std::any_of function

Download  Run Code

Output:

Key found

That’s all about determining whether a given key exists in a map or not in C++.