How to Iterate over a map in C++

In this article, we will discuss three different ways to Iterate or Loop over a Map in C++.

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

std::map<std::string, int> wordFrequency{
                                    {"this", 22},
                                    {"why", 33},
                                    {"what", 67},
                                    {"how", 41} };

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

1. Using STL Iterator

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

// Create a map iterator and point to beginning of map
std::map<std::string, int>::iterator it = wordFrequency.begin();

Now, we can use this iterate over all key-value pairs of map. We can do that by incrementing the iterator until it reaches the end of map i.e. till it is not equal to the map::end(). Also, map internally stores element in a std::pair format, therefore during iteration, we can access each key & value using the current iterator. Like this,

// Iterate over the map using Iterator till end.
while (it != wordFrequency.end())
{
    // Accessing KEY from element pointed by it.
    std::string word = it->first;

    // Accessing VALUE from element pointed by it.
    int count = it->second;

    std::cout << word << " :: " << count << std::endl;

    // Increment the Iterator to point to next entry
    it++;
}

Each iterator is pointing to a pair containing key & value. So, we can use the first and second attributes of pair through iterator to access the key & value.

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

#include <iostream>
#include <iterator>
#include <string>
#include <map>

int main()
{

    std::map<std::string, int> wordFrequency{
                                        {"this", 22},
                                        {"why", 33},
                                        {"what", 67},
                                        {"how", 41} };

    // Create a map iterator and point to beginning of map
    std::map<std::string, int>::iterator it = wordFrequency.begin();

    // Iterate over the map using Iterator till end.
    while (it != wordFrequency.end())
    {
        // Accessing KEY from element pointed by it.
        std::string word = it->first;

        // Accessing VALUE from element pointed by it.
        int count = it->second;

        std::cout << word << " :: " << count << std::endl;

        // Increment the Iterator to point to next entry
        it++;
    }
    return 0;
}

Output:

how :: 41
this :: 22
what :: 67
why :: 33

2. 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 using auto keyword. For this, we don’t need iterator and it also requires less amount of code. Like this,

for (auto& pairObj: wordFrequency)
{
    std::cout<< "Key : "  << pairObj.first << " || "
                << "Value : "<< pairObj.second << std::endl;
}

The For Loop will iterate over all key-value pairs, and during each iteration variable pairObj will contain a reference to the a key-value pair from the map. There are no iterators involved here.

Check out the following example,

#include <iostream>
#include <iterator>
#include <string>
#include <map>

int main()
{

    std::map<std::string, int> wordFrequency{
                                        {"this", 22},
                                        {"why", 33},
                                        {"what", 67},
                                        {"how", 41} };

    for (auto &pairObj : wordFrequency)
    {
        std::cout << "Key : " << pairObj.first << " || "
                  << "Value : " << pairObj.second << std::endl;
    }
    return 0;
}

Output:

Key : how || Value : 41
Key : this || Value : 22
Key : what || Value : 67
Key : why || Value : 33

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

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

3. Using Lambda & std::for_each()

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,

#include <iostream>
#include <iterator>
#include <string>
#include <algorithm>
#include <map>

int main()
{
    std::map<std::string, int> wordFrequency{
        {"this", 22},
        {"why", 33},
        {"what", 67},
        {"how", 41}};

    std::for_each(
        wordFrequency.begin(),
        wordFrequency.end(),
        [](auto &element)
        {
            std::cout << "Key : " << element.first << " || "
                      << "Value : " << element.second << std::endl;

        });
    return 0;
}

Output:

Key : how || Value : 41
Key : this || Value : 22
Key : what || Value : 67
Key : why || Value : 33

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

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

Summary

Today we learned about three different ways to iterate over a map in C++.

1 thought on “How to Iterate over a map in C++”

  1. Pingback: std::map Tutorial Part 1: Usage Detail with examples – thisPointer.com

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top