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; } |
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:
- Using a ranged based for loop
- Using begin() and end()
- Using Iterators
- Using std::for_each and lambda function