This is the 9th Part of Tutorial Series on unordered_map. In this tutorial, we will discuss, how to modify the value associated with a key in an unordered_map in C++.

An unordered_map provides fast access to its elements via their keys, and therefore modifying the value of an existing key can be done in several ways. Let’s look at them one by one.

Using the [] Operator

The [] Operator of unordered_map returns a reference to the value associated with the gven key. Therefore, if the key already exists in the map, you can use the [] operator to access and modify its value directly. If the key does not exist, this method will create a new element with that key.

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

int main() 
{
    std::unordered_map<std::string, int> wordFrequency = {
                                                    {"Where", 2},
                                                    {"How", 3},
                                                    {"That", 4}
                                                };

    // Sets the frequency for the word "Why" to 1
    wordFrequency["Why"] = 1;  

    // Changes the frequency for "Why" to 2
    wordFrequency["Why"] = 2; 

    // Iterate over unordered_map in C++
    for (const auto& pair : wordFrequency) 
    {
        std::cout << pair.first << " :: " << pair.second << std::endl;
    }
    return 0;
}

Output:

Why :: 2
That :: 4
How :: 3
Where :: 2

In this snippet, wordFrequency[“Why”] = 1 either modifies the value associated with the key “Why” or inserts a new element with this key and sets its value to 1. The second line, wordFrequency[“Why”] = 2, then updates the value associated with “Why” to 2. If the key does not exist in the map, the [] operator automatically creates a new element with that key.

Using the at() Method

The at() function of unordered_map accepts a key as argument and returns a reference to the value associated with the gven key. It seems to be same as [] Operator, but
it provides access to the value associated with a key with bounds checking. It throws a std::out_of_range exception if the key does not exist. This method is safer than the [] operator as it ensures the key already exists in the map.

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

int main()
{
    std::unordered_map<std::string, int> wordFrequency = {
                                                    {"Where", 2},
                                                    {"How", 3},
                                                    {"That", 4}};

    try
    {
        // Changes the frequency for "Where" to 3
        wordFrequency.at("Where") = 3; 
    }
    catch (const std::out_of_range &e)
    {
        std::cout << "Key not found: " << e.what() << 'n';
    }

    // Iterate over unordered_map in C++
    for (const auto &pair : wordFrequency)
    {
        std::cout << pair.first << " :: " << pair.second << std::endl;
    }
    return 0;
}

Output:

That :: 4
How :: 3
Where :: 3

In this try-catch block, wordFrequency.at(“Where”) attempts to access the value associated with the key “Where”. If the key is not found, a std::out_of_range exception is thrown, which is then caught and handled in the catch block. This method is ideal when you want to avoid inadvertently inserting new elements into the unordered_map.

Using the find() Method

The unordered_map::find() function is an effective way to check if a key exists in an unordered_map without the risk of modifying the unordered_map or throwing an exception. It returns an iterator to the found element or to the end of the unordered_map if the key does not exist.

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

int main()
{
    std::unordered_map<std::string, int> wordFrequency = {
                                                    {"Where", 2},
                                                    {"How", 3},
                                                    {"That", 4}};

    // Look for key-value pair with key "How"
    auto it = wordFrequency.find("How");

    // Check if iterator is valid
    if (it != wordFrequency.end())
    {
        // Changes the frequency for "How" to 4
        it->second = 4;  
    }

    // Iterate over unordered_map in C++
    for (const auto &pair : wordFrequency)
    {
        std::cout << pair.first << " :: " << pair.second << std::endl;
    }
    return 0;
}

Output:

That :: 4
How :: 4
Where :: 2

Summary

Today, we learned different ways to modify the contents of 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.