How to use range-based for() loop with std::map?


Here we will see how to use the range based for loop for std::map type objects. In C++, we know that there are map type objects. That can store key value pairs. The map basically stores the pair objects. This pair object is used to store one key and corresponding value. These keys and values are implemented using templates, so we can use any type of data.

To use the range based for loop, we can define for loop that can iterate through each pair of the map. Let us see the code to get the better idea.

Example Code

#include<iostream>
#include<map>
using namespace std;
main() {
   map<char, string> my_map;
   my_map.insert(pair<char, string>('A', "Apple"));
   my_map.insert(pair<char, string>('B', "Ball"));
   my_map.insert(pair<char, string>('C', "Cat"));
   my_map.insert(pair<char, string>('D', "Dog"));
   my_map.insert(pair<char, string>('E', "Eagle"));
   my_map.insert(pair<char, string>('F', "Flag"));
   my_map.insert(pair<char, string>('G', "Ghost"));
   my_map.insert(pair<char, string>('H', "Hill"));
   my_map.insert(pair<char, string>('I', "India"));
   my_map.insert(pair<char, string>('J', "Jug"));
   for(auto& key_val : my_map) {
      cout << "The " << key_val.first << " is pointing to: " << key_val.second << endl;
   }
}

Output

The A is pointing to: Apple
The B is pointing to: Ball
The C is pointing to: Cat
The D is pointing to: Dog
The E is pointing to: Eagle
The F is pointing to: Flag
The G is pointing to: Ghost
The H is pointing to: Hill
The I is pointing to: India
The J is pointing to: Jug

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements