Iterate through map in C++

In this tutorial, we will discuss how to iterate over a map in C++.

There are multiple ways by which we can iterate through a map. We will understand various ways one by one.

1. Using Range-Based for Loop(introduced in C++11)

This is the simplest way of iterating through a map. In this method, we use the auto(used to declare a variable that has a complicated type) keyword to iterate over the map.

Let’s see an example:

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, string> city_state = {{"Mumbai", "Maharashtra"},
                                      {"Jaipur", "Rajasthan"},
                                      {"Bhopal", "Madhya Pradesh"}};
    
    
    for(auto m: city_state)                             //iterate using auto
    {
                                                        
        cout << m.first << " : " << m.second << endl;   // m.first is the key and m.second is the value 
    }

    return 0;
}
Output:

Bhopal : Madhya Pradesh
Jaipur : Rajasthan
Mumbai : Maharashtra

2. Using Range-Based for Loop(introduced in C++17)

The range-based for loop in C++17 provides more flexibility to the programmers. In this method, the key value parameters can be defined in the for loop only to easily access them inside the body of the loop.

Example:

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, string> city_state = {{"Bhopal", "Madhya Pradesh"},
                                      {"Mumbai", "Maharashtra"},
                                      {"Jaipur", "Rajasthan"}
                                      };
    
    
    for(auto [key, val] : city_state)
    {
        cout << key << ": " << val << endl;
    }

    return 0;
}
Output:

Bhopal: Madhya Pradesh
Jaipur: Rajasthan
Mumbai: Maharashtra

3. Using begin() and end()

The begin() and end() are the member functions of container classes that return the iterator to the first and the last key-value pair in a map. We can use them to traverse a map.

Example:

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, string> city_state = {{"Bhopal", "Madhya Pradesh"},
                                      {"Mumbai", "Maharashtra"},
                                      {"Jaipur", "Rajasthan"}
                                      };
    
    
    for(auto i=city_state.begin(); i!=city_state.end(); i++)
    {
        cout << i->first << ": " << i->second << endl;
    }


    return 0;
}
Output:

Bhopal: Madhya Pradesh
Jaipur: Rajasthan
Mumbai: Maharashtra

Note: In an unordered_map, elements will be in random order!

Leave a Reply

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