In this article we will discuss how to find if a given key exists in map or not.

Map internally store elements in Key-Value pair. It provides 2 member functions to check if a given key exists in map i.e.

  • std::map::find
  • std::map::count

Check if map contains a key using std::map::count

std::map provides a member function count() i.e.

It finds & returns the count of number of elements in map with key K. As map contains elements with unique key only. So, it will return 1 if key exists else 0.

Suppose we have map of string & int i.e.

Let’s check if key ‘hat’ exists in the map or not i.e.

Complete example as follows,

Output:

std::map::count just tells if the given key exists in map or not. But what if we also want to access the value
associated with the given key. For that map provides another member function i.e. std::map::find

Check if map contains a key using std::map::find

std::map provides a member function find() i.e.

It checks if any element with given key ‘k’ exists in the map and if yes then it returns its iterator else
it returns the end of map.

Suppose we have map of string & int i.e.

Let’s check if key ‘hat’ exists in the map or not i.e.

Complete example as follows,

Output:

To Compile the above code use following command,

g++ –std=c++11 example.cpp