C++ Program to Iterate Over a Dictionary


Although C++ lacks dictionaries, it does have a structure akin to them called a map. Two valueskey and mapped valuesare contained in each entry of a map. Each item is indexed using the key value, whereas the mapped values are the values connected to the keys. The mapped values may or may not be unique, but the keys are always unique. In this tutorial, we'll look at iterators and how they work with maps.

Iterators in C++

An iterator object points to one element in a range of elements. Iterators are generally used with arrays and containers like vectors and have a particular set or operations that can be used to point to a specific element in a given range. Iterators point to the memory location of a particular element of a range and can be incremented or decremented to point to a different element present in the range or the container. Let’s take a look at how an iterator works.

Syntax

<container_type> :: iterator iterator_name;

Let’s take an example −

Example

#include <iostream>
#include <iterator>
#include <vector>

using namespace std;

int main(){
   //we are using a vector to demonstrate the working of an iterator
   vector<int> myVec = { 10, 20, 30, 40, 50 };
     
   // creating an iterator
   vector<int>::iterator it;
     
   // iterating through the elements
   cout << "The elements are: ";
   //the begin and end are used to define the range
   for (it = myVec.begin(); it < myVec.end(); it++)
      cout << *it << " ";
     
   return 0;   
}

Output

The elements are: 10 20 30 40 50

Using iterators to iterate through a map

It is a fairly simple process and the same as iterating through other containers.

Syntax

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

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

In C++, maps are deemed as ordered collections, meaning the components are sorted by the values of their key attributes. Red-black trees are used to implement maps in memory, and all operations have a logarithmic time complexity. While iterating through maps, we have to use iterators, or otherwise, there is no other easier way to access all the elements in a map.

Updated on: 13-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements