![]() |
VOOZH | about |
In C++, a map is a container that stores elements formed by a combination of a key value and a mapped value. A range-based for loop is a feature added in C++11 to iterate over containers. In this article, we will learn how to use a range-based for loop with a map in C++.
Input:
myMap: { {1, “John”}, {2, “Adam”} }
Output:
1: John
2: Adam
We can use the range-based for loop with a std::map to replace any other loop and simplify the code. The range-based for loop will take the name of the map and iterator over each element in the container.
Ranged-based for loop with read-only iterator Apple: 50 Banana: 25 Mango: 30 Orange: 20 Ranged-based for loop with writable iterator Apple: 60 Banana: 35 Mango: 40 Orange: 30
Time Complextiy: O(N logN), where N is the number of elements.
Space Complexity: O(1)