This is the 4th Part of Tutorial series on unordered_map. In this tutorial, we will discuss how to Insert key-value pairs in an unordered_map.

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.

Inserting elements into an unordered_map in C++ is important for managing key-value pairs in this container type.

Different ways to to Insert Elements in unordered_map

Using the insert() Method

The insert method can be used in different ways to add new elements to an unordered_map.

Inserting a single pair using std::make_pair:

unordered_map<string, int> wordFrequency;
wordFrequency.insert(std::make_pair("Why", 1));

std::make_pair is a standard library function that creates a std::pair object, which is the element type for unordered_map. Here, std::make_pair(“Why”, 1) creates a pair where “Why” is the key and 1 is the value. The insert method in this code adds the created pair to the unordered_map. If a pair with the same key already exists, the insert operation will not overwrite the existing pair.

Inserting a single pair using uniform initialization (C++11 and later):

wordFrequency.insert({"Where", 2});

This feature was introduced in C++11, known as uniform initialization. It simplifies the syntax for inserting elements. {“Where”, 2} directly constructs a std::pair without explicitly calling std::make_pair. Like the previous method, this insert operation adds a new key-value pair to the unordered_map. It’s more concise and often preferred for its readability.

Inserting another unordered_map or part of it (range insert):

unordered_map<string, int> anotherWordFrequency = {{"How", 3}, {"That", 4}};
wordFrequency.insert(anotherWordFrequency.begin(), anotherWordFrequency.end());

This method involves inserting a range of elements from another unordered_map. anotherWordFrequency.begin() and anotherWordFrequency.end() specify the beginning and end of the range to be inserted. Range insert is particularly useful when you need to merge two unordered_maps or insert a subset of another unordered_map. It’s an efficient way to combine or transfer elements between maps.

Using the [] Operator:

The [] operator in unordered_map provides a simple and intuitive way to insert elements or modify existing ones. If the key does not exist, a new element with that key is created.

unordered_map<string, int> wordFrequency;
wordFrequency["Why"] = 1;   // Inserts key "Why" with value 1
wordFrequency["Where"] = 2; // Inserts key "Where" with value 2

When you use wordFrequency[“Why”] = 1, the operator checks if the key “Why” exists. If it doesn’t, a new element with key “Why” and value 1 is created and added to the map. If it does exist, its value is updated to 1.
Important Points:
Automatic Element Creation: If a key doesn’t exist, the [] operator automatically creates a new element with that key.
Direct Value Modification: It allows direct modification of the value associated with a key. This is particularly useful for updating values.
Ease of Use: The syntax is straightforward, making code more readable and easier to understand.

Using the emplace() Method** (C++11 and later):

The emplace method constructs the element in-place and might be more efficient than insert, avoiding the creation of a temporary object.

unordered_map<string, int> wordFrequency;

wordFrequency.emplace("How", 3);
wordFrequency.emplace("That", 4);

The emplace() function constructs the element in place within the unordered_map. For example, wordFrequency.emplace(“How”, 3) creates a pair with “How” as the key and 3 as the value and inserts it into the map.
Important Points:
In-Place Construction: It directly constructs elements within the map, potentially saving overhead compared to methods that first create a temporary object.
Efficiency: Often more efficient than insert, especially with complex data types or when constructing objects directly in the container.
Duplicate Key Handling: Similar to insert, if a key already exists, emplace will not overwrite the existing key-value pair, preserving the integrity of existing data.

The complete example

Here’s an example demonstrating these methods:

#include <iostream>
#include <string>
#include <unordered_map>

int main() 
{
    std::unordered_map<std::string, int> wordFrequency;

    // Using insert with make_pair
    wordFrequency.insert(std::make_pair("Why", 1));

    // Using insert with initializer list
    wordFrequency.insert({"Where", 2});

    // Using the [] operator
    wordFrequency["How"] = 3;

    // Using emplace
    wordFrequency.emplace("That", 4);

    // Output the contents of the map
    for (const auto& pair : wordFrequency) {
        std::cout << "'" 
             << pair.first 
             << "' appears " 
             << pair.second
             << " times." 
             << std::endl;
    }

    return 0;
}

Output:

'That' appears 4 times.
'How' appears 3 times.
'Where' appears 2 times.
'Why' appears 1 times.

Summary

In this tutorial, we learned about different methods (insert with make_pair, insert with an initializer list, the [] operator, and emplace) are used to insert word-frequency pairs into the unordered_map named wordFrequency. The for-loop at the end iterates over the map and prints each word and its frequency.

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.