Given an ordered or an unordered map and a key in C++, increment the map value associated with that key.

The idea is to use the unordered_map::find function that searches the container for a key and returns an iterator to it, or the unordered_map::end if the key is not found.

Once the key is found, we can increment its value using the ++ operator on the second member function of the pair pointed by the iterator. If the key is not found, we can insert it into the map with value 1 using unordered_map::insert with std::make_pair.

Download  Run Code

Output:

{D, 1}
{C, 2}
{B, 2}
{A, 3}

 
We can also use operator[], which makes this very easy. It returns a reference to the mapped value for the specified key. If the key does not exist in the map, it inserts a new pair with that key and the default value of 0 (for numeric data types) and returns a reference to it. Once we reference the mapped value of a key, we can use the ++ operator to increment its value.

Download  Run Code

Output:

{D, 1}
{C, 2}
{B, 2}
{A, 3}

That’s all about incrementing the map value associated with a key in C++.