How we can translate Python dictionary into C++?

PythonProgramming

A python dictionary is a Hashmap. You can use the map data structure in C++ to mimic the behavior of a python dict. You can use map in C++ as follows:

#include <iostream>
#include <map>
using namespace std;
int main(void) {
   /* Initializer_list constructor */
   map<char, int> m1 = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   cout << "Map contains following elements" << endl;
   for (auto it = m1.begin(); it != m1.end(); ++it)
   cout << it->first << " = " << it->second << endl;
   return 0;
}

This will give the output

The map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5

Note that this map is equivalent to the python dict:

m1 = {
   'a': 1,
   'b': 2,
   'c': 3,
   'd': 4,
   'e': 5
}
raja
Published on 18-Apr-2018 15:39:17
Advertisements