C++ Program to Create a Dictionary with a Dictionary Literal


Dictionaries aren’t present in C++, but it has a similar structure called map. Each entry of a map has a couple of values in it, which are key and mapped values. The key value is used for indexing each entry, whereas the mapped values are the values that are associated with the keys. Keys are unique, but the mapped values may or may not be unique. In this article, we take a look at how to initialize a map object and create it from another map object.

Creating an empty map

To create a map object, we need to import the STL class std::map. When we create a map object, an empty map is created. We have to note that we have to mention the type of the key and the mapped value while creating a map object.

Syntax

#include <map>
map <data_type 1, data_type 2> map_name;

Let’s take an example −

Example

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <string, string> mmap;

   //inserting some values
   mmap.insert({"Fruit", "Mango"});
   mmap.insert({"Tree", "Oak"});
   mmap.insert({"Vegetable", "Eggplant"});

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

   return 0;
}

Output

Fruit: Mango
Tree: Oak
Vegetable: Eggplant

Creating a map from another map

There may be multiple circumstances when we might need to copy a map or need to preserve the value. For that, we can make a map from another map using the copy constructor of the map class. We need to make sure the datatypes of both the map objects match.

Syntax

#include <map>
map <data_type 1, data_type 2> map_name1;
map <data_type 1, data_type 2> map_name2(map_name1);

Example

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <string, string> mmap = {{"Fruit", "Litchi"}, {"Tree", "Birch"}, {"Vegetable", "Potato"}};

   //copy the elements using the copy constructor
   map <string, string> copyMap(mmap);

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

Output

Fruit: Litchi
Tree: Birch
Vegetable: Potato

Conclusion

Maps are ordered collections in C++, which means the elements are sorted according to their key values. Maps are implemented using red−black trees in memory and offer a logarithmic time complexity for all operations. In this article, we knew the way how to create a copy of a map object using a copy constructor.

Updated on: 13-Dec-2022

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements