Iterating over a map by using an STL Iterator

We can create an iterator of std::map (or std::unordered_map), initialize it to the start of the map, and increment it till the end to traverse the map.

Example:

C++




// C++ program to traverse a unordered_map using
// std::for_each() and lambda()
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <unordered_map>
  
int main()
{
    // Map created
    std::unordered_map<std::string, int> ExampleMap;
  
    // elements are inserted into unordered_map
    ExampleMap.insert(
        std::pair<std::string, int>("Sunday", 1));
    ExampleMap.insert(
        std::pair<std::string, int>("Monday", 2));
    ExampleMap.insert(
        std::pair<std::string, int>("Tuesday", 3));
    ExampleMap.insert(
        std::pair<std::string, int>("Wednesday", 4));
    ExampleMap.insert(
        std::pair<std::string, int>("Thursday", 5));
    ExampleMap.insert(
        std::pair<std::string, int>("Friday", 6));
    ExampleMap.insert(
        std::pair<std::string, int>("Saturday", 7));
  
    // unordered_map iterator created
    // iterator pointing to start of unordered_map
    std::unordered_map<std::string, int>::iterator it
        = ExampleMap.begin();
  
    // Iterating over the unordered_map till unordered_map
    // end.
    std::for_each(ExampleMap.begin(), ExampleMap.end(),
                  [](std::pair<std::string, int> p) {
                      std::cout << p.first
                                << " :: " << p.second
                                << std::endl;
                  });
    return 0;
}


Output

Friday :: 6
Monday :: 2
Saturday :: 7
Sunday :: 1
Thursday :: 5
Tuesday :: 3
Wednesday :: 4

Traversing a Map and unordered_map in C++ STL

The maps are described as mapped associative containers for elements where each element has a key and value assigned to it. Another form of map container seen in the C++ STL is the unordered map. It is the same as map containers just that they don’t store the data in sorted order.

We can traverse map and unordered_map using 4 different ways  which are as follows:

  1. Using a ranged based for loop
  2. Using begin() and end()
  3. Using Iterators
  4. Using std::for_each and lambda function

Similar Reads

1. Using a Range Based for Loop

We can use a range-based for loop to iterate over a map or an unordered_map in C++....

2. Traversing using begin() and end()

...

3. Iterating over a map by using an STL Iterator

...

4. Iterating over a map by using std::for_each and lambda function

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 or unordered_map respectively. We can use them to traverse over a map or an unordered_map....