Check if an unordered map contains a key in C++

This tutorial will see how to check if an unordered map contains a key or not in C++. Unordered maps are similar to dictionary data types. The unordered map is a container that stores the element in form of a key-value pair. The key is unique and used to identify the particular associated mapped value associated with it.

Algorithm

Step 1: In the main function define the unordered map of the key and value of both integer types. Define the key and values of the unordered map. Define two key values that are to be checked in an unordered map.

• `unordered_map<int,int> umap` : It is a predefined function from unordered_map library used to define unordered map. Here the first int is the datatype of a key and the second int is the datatype of value. umap is the name of an unordered map.

Step 2: Define a function of string type to check whether the key is present or not. Pass the unordered map instance and an integer key as a parameter to the function.

Step 3: check for the key in the unordered map if the key iterator exceeds the end of the map it means a key is not present in an unordered map so return the result as a string “Not present”. Else return “key is present” in the unordered map.

• `um.find(key)`: It returns the iterator of the key element passed.
• `um.end()`: It returns the iterator of the position past the last element of the unordered map.

Step 4: Call the check function in the main function and pass the previously defined unordered map and keys to the function and output the result.

C++ code to Check if an unordered map contains a key

Here is the full code for reference

```//C++ code to check if an unordered_map contains a key
#include <bits/stdc++.h>
using namespace std;
string check_key(unordered_map<int, int> um,int key)      //function to check the presence of key in map
{
if (um.find(key) == um.end())                          //if Key past end of map
{
return "Key is not Present in unordered map";           //then return key is not present
}
else
{
return "Key is present in unordered map";               //else return present
}
}
int main()
{
unordered_map<int, int> umap;                          //declare empty unordered map
umap[1] = 4;                                           // Initialising keys and mapped values
umap[2] = 3;
umap[4] = 6;
umap[6] = 7;
int key1 = 5, key2 = 4;                               // Keys to be checked
cout<<key1<<": "<< check_key(umap, key1)<<'\n';       //output the result for check 1 and 2
cout<<key2<<": "<< check_key(umap, key2);
}```

Output:

```5: Key is not Present in unordered map
4: Key is present in unordered map```

Also, refer to Check if a key is present in a C++ map