Range-Based For Loop with a Map in C++
Last Updated :
28 Feb, 2024
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++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int > priceOfFruits = { { "Apple" , 50 },
{ "Mango" , 30 },
{ "Banana" , 25 },
{ "Orange" , 20 } };
cout << "Ranged-based for loop with read-only iterator"
<< endl;
for ( const auto eachPair : priceOfFruits) {
cout << eachPair.first << ": " << eachPair.second
<< endl;
}
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)
Share your thoughts in the comments
Please Login to comment...