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++.
Example:
Input:
myMap: { {1, “John”}, {2, “Adam”} }
Output:
1: John
2: Adam
Range-Based for Loop with a Map in C++
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.
C++ Program to Traverse Map with Range Based for Loop
C++
// C++ Program to Use a Range-Based For Loop with a Map #include <iostream> #include <map> using namespace std;
// Driver Code int main()
{ // Decalarion and intitalization of the map with key of
// type string and value of type int
map<string, int > priceOfFruits = { { "Apple" , 50 },
{ "Mango" , 30 },
{ "Banana" , 25 },
{ "Orange" , 20 } };
// Printing the key and values of the map
cout << "Ranged-based for loop with read-only iterator"
<< endl;
for ( const auto eachPair : priceOfFruits) {
cout << eachPair.first << ": " << eachPair.second
<< endl;
}
// Modifying the values of the map and then printing the
// key and values of the map
cout << "Ranged-based for loop with writable iterator"
<< endl;
for ( auto & eachPair : priceOfFruits) {
eachPair.second += 10;
cout << eachPair.first << ": " << eachPair.second
<< endl;
}
return 0;
} |
Output
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)