C++

How to Create a Dictionary in C++

In programming, a dictionary offers a practical method to map specific values to keys and making those values accessible.

Dictionaries are widely used in programming because they offer fast lookup times and provide a convenient way to organize and access the data. They are particularly useful when you need to store and retrieve the data based on a unique identifier (the key).

In C++, there is no built-in container called “dictionary” in the Standard Template Library (STL). However, the functionality of a dictionary can be achieved using the “std::map” or “std::unordered_map” containers. These containers provide the key-value storage and retrieval which makes them suitable for dictionary-like operations.

Both “std::map” and “std::unordered_map” offer similar functionality but have different performance characteristics. Based on your unique requirements and preferences, you have the freedom to choose the best feasible option.

We will carry out some examples to demonstrate the usage of “std::map” and “std::unordered_map” in C++.

Method 1: Utilizing the Std::Map

In C++, “std::map” is a container that is provided by the Standard Template Library (STL) that implements an associative array or dictionary-like data structure. The “std::map” container in C++ is designed to store the key-value pairs efficiently which allows for quick lookup, insertion, and deletion operations based on the keys. One notable characteristic is that each key within the “std::map” must be unique.

In the case where you attempt to include a key-value combination with a key that currently exists within the map, the insertion operation will be disregarded, and the present value that is linked with that key will remain unaltered.

The “std::map” supports various associative operations including insertion, deletion, searching for a key, counting occurrences, and finding the range of elements based on keys.

Let’s create an example that demonstrates the usage of “std::map” to create a dictionary-like structure:

#include <iostream>

#include <map>

int main() {

  std::map<std::string, int> dict;

  dict["Green"] = 4;

  dict["White"] = 2;

  dict["Purple"] = 9;

  std::cout << "Value of White: " << dict["White"] << std::endl;

  for (const auto& pair : dict) {

    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;

  }

  return 0;

}

We start by adding the needed header files for this program. The two header files that we added here are <iostream> and <map>. Including the <iostream> header allows you to use the input/output stream functionalities in your C++ code. The <iostream> header is part of the C++ Standard Library and provides definitions for the standard input/output streams (std::cin, std::cout, etc.) and their associated operations.

Whereas, including the <map> header allows you to use the “std::map” container and its associated functionalities in your C++ code. The <map> header is part of the Standard Template Library (STL) and provides the necessary definitions and operations to work with the “std::map” container. Once you included the <map> header, you can use the “std::map” container and its member functions in your code.

Inside the main() function, the “std::map” named “dict” is declared which stores the key-value pairs. The “std::map” is the template class that represents a map container in C++. The “std::map” container enables us to establish the associations between keys and values where the keys and values can be of different types.

The declaration <std::string, int> specifies the particular types that are used for keys and values within the map. In this case, the keys are of type “std::string” which represents the strings, and the values are of type “int” which represents the integers.

By declaring the std::map<std::string, int> dict;, we create an empty map where we can store the key-value pairs with the keys as the strings and the values as the integers. We can later insert, modify, or retrieve the key-value pairs using the “dictionary” object.

The key-value pairs are inserted into the dict using the subscript operator. The format for every key-value pair is key = value. We have three keys – “Green”, “White”, and “Purple” – with keys 4, 2, and 9, respectively. The program accesses and outputs the value that is associated with the “Green” key using the subscript operator []. It presents the “Value of Green: ” message followed by the value that is associated with the corresponding key.

A range-based for-loop is used to iterate over the dict. For every entry in the dictionary, the pair variable contains two members: the first member represents the key, and the second member represents the value. The program outputs the key and value of each element. The main function returns 0 to signal the conclusion of the program.

The output is provided in the following image:

Method 2: Utilizing the Std::Unordered_Map

The “std::unordered_map” is a container in C++ that provides an unordered associative array or dictionary-like data structure. The container stores the key-value pairs and facilitate fast operations to look up, insert, and delete the elements based on their respective keys. The keys are unique within the “std::unordered_map” and the elements are not ordered.

Let’s implement the “std::unordered_map” container in a C++ program to create a dictionary.

#include <iostream>

#include <unordered_map>

int main() {

  std::unordered_map<std::string, int> colors;

  colors["Acrylic"] = 11;

  colors["Oil"] = 8;

  colors["Pastel"] = 6;

  std::cout << "Value of Acrylic: " << colors["Acrylic"] << std::endl;

  for (const auto& pair : colors) {

    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;

  }

  return 0;

}

In this example, we include the necessary headers <iostream> and <unordered_map>. In the main function, define the std::unordered_map<std::string, int> named “colors”. We insert the key-value pairs into the colors using the subscript operator []. The key-value pairs that we specified here are Acrylic = 11, Oil = 8, and pastel = 6.

Using the subscript operator [], we retrieve and display the value that is associated with the “Acrylic” key. The output shows “Value of Acrylic:” followed by the corresponding value.

By utilizing a range-based for loop, we iterate through the colors in the “std::unordered_map”. Each iteration assigns the current key-value pair to the pair variable where the first member represents the key and the second member represents the value. The program proceeds to exhibit both the key and value for each element that is contained within the map. Lastly, the program returns 0 which shows that the execution is successful.

The snapshot of the resultant key-value pairs is attached in the following:

The “std::unordered_map” provides fast access and insertion operations based on the keys, typically with constant or near-constant time complexity. However, the elements in the map are not ordered based on the keys, unlike in the “std::map”.

Conclusion

Creating a dictionary in C++ can be achieved by utilizing the “std::map” and “std::unordered_map” containers. Both these methods have been thoroughly elaborated on in this post. We carried out a practical demonstration for you to comprehend the concept better. The “std::map” container provides an ordered key-value pair as the output based on the keys. Whereas the “std::unordered_map”, despite taking the key-value pair too, provides the key-value pair output with unordered keys. Both techniques are equally effective and can be implemented according to the user’s need.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.