C++ Program to Print a Dictionary


Maps are a special type of container in C++ where each element is a pair of two values, the key value and the mapped value. The key value is used to index each item, and the mapped values are the values associated with the keys. The keys are always unique, regardless of whether the mapped values are. To print a map element in C++, we have to use iterators. One element in a group of items is indicated by an iterator object. Iterators primarily work with arrays and other types of containers, such as vectors, and they have a specific set of operations that may be used to identify a specific element inside a certain range. Iterators can be increased or decremented to refer to a different element that is present in the range or the container. Iterators point to the memory location of a specific element of a range.

Printing maps in C++ using iterators

First, we take a look at the syntax of how to define iterators to print maps.

Syntax

map<datatype, datatype> myMap;
map<datatype, datatype > :: iterator it;
for (it = myMap.begin(); it < myMap.end(); it++)
      cout << itr->first << ": " << itr->second << endl;

Alternative way will be something like this −

map<datatype, datatype> mmap;
for (auto itr = my.begin(); itr != mmap.end(); ++itr) {
   cout << itr->first << ": " << itr->second << endl;
}

Let’s take an example using both the methods −

Example

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <string, string> mmap = {{"City", "Berlin"}, {"Country", "Germany"}, {"Continent", "Europe"}};
   map <string, string>::iterator itr;

   //iterating through the contents
   for (itr = mmap.begin(); itr != mmap.end(); ++itr) {
      cout << itr->first << ": " << itr->second << endl;
   }
   return 0;
}

Output

City: Berlin
Continent: Europe
Country: Germany

Using the second method −

Example

#include <iostream>
#include <map>
using namespace std;

int main() {
   //initialising the map
   map <string, string> mmap = {{"City", "London"}, {"Country", "UK"}, {"Continent", "Europe"}};

   //iterating through the contents
   for (auto itr = mmap.begin(); itr != mmap.end(); ++itr) {
      cout << itr->first << ": " << itr->second << endl;
   }
   return 0;
}

Output

City: London
Continent: Europe
Country: UK

Conclusion

To display the contents of a map in C++, we have to use iterators otherwise it is hard to print out the values. Using iterators it is very easy to go through all the entries in the map and display their values.

Updated on: 13-Dec-2022

936 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements