std::map : The C++ dictionary class

std::map is the C++ standard library implementation of  a dictionary. It contains key-value pairs where the keys are all unique and the key values are used to find the associated values, much like a real-world dictionary. The map is, just like most of the standard library, implemented using templates and the types of the keys and the values are given when you create the map. Some examples of maps:

Each element of the map is of the type std::map<K, V>::value_type which is just a redefinition of std::pair<const K, V>.

Getting one element

To get the value associated with a specific key, use the bracket operator ([]). This operator will create the key-value pair if it doesn’t exist already.

Checking if a key exists in map

There are two ways to check if a key exists in a map.

  1. Using the function std::map::count(). This returns the number of keys which matches the queried key, and since all keys in the std::map are unique can this only be zero or one. This is a good way to do it if you just need to see if the key exists and don’t need to do anything with the map.
  2. Using the function std::map::find(). This returns an iterator to the found object, or std::map::end() if the object is not found. This is a better choice if you need to update the map, since you will get an iterator to the found key value pair.


To iterate over all elements in the dictionary use range-based for:

or much simpler using auto

Notice that it is a good idea to make the variable in the loop a reference since this avoids copying the element and gives better performance. Also if you don’t intend to change the element then you can make this clear by also making it const.

Erasing one element

You can erase one element from the map by using the function erase(…) which takes either an iterator, a key or a two iterators defining a range of values to remove.