C++ Dictionaries - C++ Programming Tutorial
C++ Course / Miscellaneous / C++ Dictionaries

C++ Dictionaries

BLUF: Mastering C++ Dictionaries is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Dictionaries

C++ is renowned for its efficiency. Learn how C++ Dictionaries enables low-level control and high-performance computing in the tutorial below.

The map data structure is an intrinsic component of C++. It serves as a data container where each element is associated with a unique key. It is essential to note that all elements stored in a C++ map must share the same data type. While the keys and values within a C++ map can have different data types, the keys themselves must be consistent in type throughout the map. To utilize a map in C++, it is necessary to include the map header file from the C++ standard library. By iterating through a map's values in a loop, it becomes possible to locate specific keys, with each iteration representing a key-value pair.

The following is how a dictionary functions in C++:

  • A dictionary type named map exists in C++ and functions similarly to a container for values that are indexed by keys.
  • There is a key for every value in the dictionary, which is also known as a map .
  • A C++ map requires that all of the values and keys have the same type; however, it is not a need for all of the values and keys to have the same type.
  • A map in C++ has to have its header file included in the C++ standard library to be used.
  • It is possible to iterate through a map's values in a loop to find the matching key; each iterated item corresponds to a key-value pair.
  • 1. Making a Dictionary in C++ Using the Initializer List Constructor

Initializing dictionaries directly using an initializer list containing key-value pairs is a convenient way to start with predefined data. This approach is particularly handy when you already know the key-value pairs you want to populate the dictionary with, providing a straightforward and efficient method for dictionary initialization in C++.

Code:

Let's consider an example to demonstrate the process of creating a dictionary using the Initializer List Constructor in C++:

Example

#include <iostream>
#include <unordered_map>
#include <string>
int main() 
{
    // Creating an unordered_map using the initializer list constructor
    std::unordered_map<std::string, int> dictionary = { {"apple", 10}, {"banana", 5}, {"cherry", 15} };
    // Accessing values by key
    std::cout << "apple: " << dictionary["apple"] << std::endl;
    std::cout << "cherry: " << dictionary["cherry"] << std::endl;
    return 0;
}

Output:

Output

apple: 10
cherry: 15

2. Use the default constructor to create a dictionary in C++:

A new dictionary is instantiated with the default constructor, followed by inserting elements using the subscript operator. This approach enables the dictionary to be extended with numerous key-value pairs based on your needs.

Code:

Let's consider an instance to demonstrate the process of constructing a dictionary using the default constructor in C++:

Example

#include <iostream>
#include <map>
#include <string>
int main() 
{
    // Creating an empty map
    std::map<std::string, int> dictionary;
    // Adding elements to the map
    dictionary["apple"] = 10;
    dictionary["banana"] = 5;
    dictionary["cherry"] = 15;
    // Accessing values by key
    std::cout << "apple: " << dictionary["apple"] << std::endl;
    std::cout << "cherry: " << dictionary["cherry"] << std::endl;
    return 0;
}

Output:

Output

apple: 10
cherry: 15

3. Use the copy constructor to create a dictionary in C++:

By employing a copy constructor, you can duplicate key-value pairs into the freshly instantiated object by taking input from another pre-existing map variable. This serves as an alternative approach to generating a new map instance. Importantly, this technique remains available for subsequent use during the program's runtime and does not shift the existing map object.

Code:

Let's consider an illustration to demonstrate the process of creating a dictionary using a copy constructor in the C++ programming language:

Example

#include <iostream>
#include <map>
#include <string>
int main() 
{
    // Creating a dictionary
    std::map<std::string, int> originalDictionary = {{"apple", 10}, {"banana", 5}, {"cherry", 15}};
    // Creating a new dictionary using the copy constructor
    std::map<std::string, int> newDictionary(originalDictionary);
    // Accessing values by key
    std::cout << "apple in new dictionary: " << newDictionary["apple"] << std::endl;
    std::cout << "cherry in new dictionary: " << newDictionary["cherry"] << std::endl;
    return 0;
}

Output:

Output

apple in new dictionary: 10
cherry in new dictionary: 15

4. Use the range-based constructor to create a dictionary in C++:

One benefit of utilizing the range-based constructor is its efficient and convenient approach to establishing dictionaries with an initial collection of key-value pairs. This technique is particularly effective when aiming to set up the dictionary with predefined data. By supplying the dictionary's contents at the time of creation, it can streamline the code and enhance its readability.

Code:

Let's consider an illustration to demonstrate the process of creating a dictionary using a range-based constructor in C++:

Example

#include <iostream>
#include <map>
#include <vector>
#include <string>
int main() 
{
    // Create a vector of key-value pairs
    std::vector<std::pair<std::string, int>> keyValuePairs = {
        {"apple", 10},
        {"banana", 5},
        {"cherry", 15}
    };
    // Create an empty map
    std::map<std::string, int> dictionary;
    // Use a range-based for loop to insert key-value pairs
    for (const auto& pair: keyValuePairs)
    {
        dictionary.insert(pair);
    }
    // Accessing values by key
    std::cout << "apple: " << dictionary["apple"] << std::endl;
    std::cout << "cherry: " << dictionary["cherry"] << std::endl;
    return 0;
}

Output:

Output

apple: 10
cherry: 15

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience