C++ Map Check if Key Exists – 2 Ways to Check

Hello everyone, In this article, we will see different ways by which we can check if a particular key exists in a map or not. Let’s first go through what a map is:

C++ map stores information in <key, value> pairs and we can access the value field from the key in O(logn) time. Now the problem is to check if there exists a particular key in the map or not.

Method 1: Using map::find

We can take the help of the standard library function find for map. map::find returns an iterator to the <key, value> pair if the key exists or it points to the standard iterator end in the map. So if for any particular key if find is returning an iterator pointing to the standard operator end then we can say that map doesn’t have that particular key. Here is the code: 

The time complexity to check is the same as map::find function which is O(logn).

Method 2: Using map::count

We can also make use of the c + + count method which returns 1 if the particular key is present otherwise returns 0. Here is the code illustrating the same:

The time complexity for the above code is O(logn) as well. This is widely used to check if a key is present or not.

Note: If the particular key is not present and if somewhere we use it then the key will be created in the map and initiated default value (0 for int. “” for string) will be created. So never check a key exists or not with the below condition:

Check the below code for better understanding: 

Leave a Comment

Your email address will not be published. Required fields are marked *