![]() |
VOOZH | about |
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:
We can use a range-based for loop to iterate over a map or an unordered_map in C++.
Example:
Element Frequency 1 4 2 1 3 2 4 1
Note: The above output is for map only. For unordered_map, the output rows can be in any order.
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.
Example:
Element Frequency 1 4 2 1 3 2 4 1
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:
Friday :: 6 Monday :: 2 Saturday :: 7 Sunday :: 1 Thursday :: 5 Tuesday :: 3 Wednesday :: 4
By using the std::for_each algorithm and lambda functions we can easily iterate over all the elements of the map. Here the lambda function will be used as a call-back function and will receive each map entry.
Example:
Friday :: 6 Monday :: 2 Saturday :: 7 Sunday :: 1 Thursday :: 5 Tuesday :: 3 Wednesday :: 4