A map is a special type of container in C, where each element is a pair of two values, namely a key value and a map value. The key value is used to index each item, and the mapped value is the value associated with the key. Regardless of whether the mapped value is unique, the key is always unique. To print map elements in C, we have to use iterators. An element in a set of items is indicated by an iterator object. Iterators are primarily used with arrays and other types of containers (such as vectors), and they have a specific set of operations that can be used to identify specific elements within a specific range. Iterators can be incremented or decremented to reference different elements present in a range or container. The iterator points to the memory location of a specific element in the range.
First, let’s look at the syntax of how to define an iterator to print a map.
map<datatype, datatype> myMap; map<datatype, datatype > :: iterator it; for (it = myMap.begin(); it < myMap.end(); it++) cout << itr->first << ": " << itr->second << endl;
The alternative is this -
map<datatype, datatype> mmap; for (auto itr = my.begin(); itr != mmap.end(); ++itr) { cout << itr->first << ": " << itr->second << endl; }
Let’s give an example of using these two methods -
#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; }
City: Berlin Continent: Europe Country: Germany
Use the second method -
#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; }
City: London Continent: Europe Country: UK
To display the contents of a map in C, we must use an iterator, otherwise it will be difficult to print out the value. Using an iterator makes it easy to iterate through all entries in a map and display their values.
The above is the detailed content of C++ program to print dictionary. For more information, please follow other related articles on the PHP Chinese website!