This is the 3rd Part of Tutorial series on unordered_map. In this tutorial, we will discuss how to Create & Initialize unordered_map in C++.

An unordered_map is an STL container that stores the data in keys-values pairs with no inherent order. It’s provided by Standard Template Library (STL) and serves best for efficient look-up, insertion, and deletion of elements.

How to Declare an Unordered_Map in C++?

To declare an unordered_map, you need to include the <unordered_map> header file first. Then we can specify the types of the key and value.

The syntax is as follows:

std::unordered_map<KeyType, ValueType> mapName;

Here, KeyType is the type of the keys and ValueType is the type of the values that the map will store.

Initializing an Unordered_Map

There are several ways to initialize an unordered_map:

Creating an empty unordered_map

std::unordered_map<string, int> wordFrequency;

The std::unordered_map<std::string, int> declares the type of our container. It’s an unordered_map that stores the key-value pairs where the key is a string (some word ) and the value is an integer (word’s frequency in some text). The above created unordered_map is empty.

Create & Initialize unordered_map with default values

We can initialize the unordered_map with an Initializer List of predefined key-value pairs. Like this,

std::unordered_map<std::string, int> wordFrequency = {
                                          {"Where", 20}, 
                                          {"How",    21}, 
                                          {"That",   19}
                                       };

The equals sign (=) followed by the curly braces {} indicates that we are initializing the wordFrequency unordered_map with an initializer list. Inside the curly braces, we provided a comma-separated list of key-value pairs, where each pair is enclosed in its own set of curly braces {}. Each pair consists of a key (a string) and a value (an integer) separated by a comma.

It created an unordered_map named wordFrequency with three key-value pairs. The key-value pairs are as follows:
– “Where” with a value of 20
– “How” with a value of 21
– “That” with a value of 19

Create empty unordered_map and add elements to it

An unordered_map also provides a function called ‘insert()’ which accepts a key-value pair as an argument and adds it to the unordered_map. In the code below, we are going to create an empty unordered_map and then call the ‘insert()’ function to insert a key-value pair into it. Before that, we are going to use the ‘make_pair()’ function, which accepts a key and a value as arguments and returns an std::pair object.

The std::make_pair() function is a utility function in C++ that is used to create and return a std::pair object. A std::pair is a simple data structure that can hold two values of potentially different types, making it useful for creating key-value pairs or pairs of related values.

We can create an empty unordered_map and then add elements to it using make_pair function. For example,

// Creating empty unordered_map
std::unordered_map<std::string, int> wordFrequency;

// Adding elements to empty unordered_map
wordFrequency.insert(std::make_pair("Where", 20));
wordFrequency.insert(std::make_pair("That", 21));
wordFrequency.insert(std::make_pair("How", 19));

We created an empty unordered_map and used the unordered_map’s insert() function to add elements to the wordFrequency unordered_map.

The std::make_pair(“Where”, 20) created a std::pair of a key “Where” (a string) and a value of 20 (an integer). This pair represents one key-value entry. This pair got added into the unordered_map using insert() function.

After executing the above code, the wordFrequency map will contain three key-value pairs:

  • “Where” with a value of 20
  • “That” with a value of 21
  • “How” with a value of 19

An important point to note here is that the ‘insert()’ function in an unordered_map can only store unique keys. If we try to insert a pair with a duplicate key, the ‘insert()’ function will not add it. Additionally, if the key already exists and we provide a duplicate key, it will not overwrite the existing value of the key.

Initalize an unordered_map using Array-like Syntax

You can also add key-value pairs to a map using the subscript operator, just like an array. For example, in the code below, we have created an unordered_map of strings to integers.

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

Now, we are going to add certain key-value pairs. To do this, we can use the subscript operator to specify the key and assign a value to it, similar to how we change the value in an array.

wordFrequency["Where"] = 20;
wordFrequency["How"] = 21;
wordFrequency["That"] = 19;

The code above will add three key-value pairs to the unordered_map. An important point to consider here is that if the given key already exists in the map, it will simply overwrite the existing value.

Creating a copy of unorderd_map

We can also create a copy of an unordered_map using its copy constructor. For example, in the following code, we have created a map of strings and integers and assigned certain values to it. Then, we can create a new copy of this unordered_map.

std::unordered_map<std::string, int> wordFrequency = {
                                          {"Where", 20}, 
                                          {"How",    21}, 
                                          {"That",   19}
                                       };

std::unordered_map<std::string, int> freq = wordFrequency;

Both copies will be distinct; they will not be linked to each other in any way. Changes made in one copy of the unordered_map will not affect the contents of the other unordered_map.

Example Code

Here’s a simple example that demonstrates declaring and initializing an unordered_map:

#include <iostream>
#include <map>
#include <unordered_map>

int main() 
{
    {
        // Create & Initialize unordered_map with default values
        std::unordered_map<std::string, int> wordFrequency = {
                                                {"Where", 20}, 
                                                {"How",    21}, 
                                                {"That",   19}
                                            };

        // Print all key-value pairs in unordered_map
        for (auto & element: wordFrequency) {
            std::cout << element.first
                    << " :: " 
                    << element.second 
                    << std::endl;;
        }
    }


    {
        // Creating empty unordered_map
        std::unordered_map<std::string, int> wordFrequency;

        // Adding elements to empty unordered_map
        wordFrequency.insert(std::make_pair("Where", 20));
        wordFrequency.insert(std::make_pair("That", 21));
        wordFrequency.insert(std::make_pair("How", 19));

        // Print all key-value pairs in unordered_map
        for (auto & element: wordFrequency) {
            std::cout << element.first
                    << " :: " 
                    << element.second 
                    << std::endl;;
        }
    }

    {
        // Creating empty unordered_map
        std::unordered_map<std::string, int> wordFrequency;

        // Initalize an unordered_map using Array-like Syntax
        wordFrequency["Where"] = 20;
        wordFrequency["How"] = 21;
        wordFrequency["That"] = 19;

        // Print all key-value pairs in unordered_map
        for (auto & element: wordFrequency) {
            std::cout << element.first
                    << " :: " 
                    << element.second 
                    << std::endl;;
        }
    }

    return 0;
}

Output:

That :: 19
How :: 21
Where :: 20

How :: 19
That :: 21
Where :: 20

That :: 19
How :: 21
Where :: 20

Summary

We learned about different ways to create and initalize an unordered_map in C++.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.