In this article we will discuss 3 different ways to Iterate over a map in C++.

Suppose we have a map of string and int as key-value pair i.e.

Now let’s see how to iterate over this map in 3 different ways i.e.

Iterate over a map using STL Iterator

First of all, create an iterator of std::map and initialize it to the beginning of map i.e.

Now, let’s iterate over the map by incrementing the iterator until it reaches the end of map. Also, map internally stores element in a std::pair format, therefore each iterator object points to an address of pair.

Access key from iterator using,

Access value from iterator using,

Complete example of iterating over a map using stl iterator is as follows,

Output:

Iterating over the map using C++11 range based for loop

C++11 provides a range based for loop, we can also use that to iterate over the map. In that case we don’t need iterate and it will take less coding. Check out the following example,

Output:

Above example is using c++11 feature. So, to compile it on linux use following command,

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

Iterating over the map using std::for_each and lambda function

We can also use an stl algorithm std::for_each to iterate over the map. It will iterate on each of the map entry and call the callback provided by us. In below example we will use a lambda function as callback. Lambda function will receive each of the map entry in a pair. Checkout complete example as follows,

Output:

Above example is using c++11 feature. So, to compile it on linux use following command,

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