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

A std::map stores its elements as key-value pairs in a sorted order of keys and provides efficient access to elements via their keys. There are different techniques to change the value associated with a key in a std::map. Let’s explore these methods.

Using the [] Operator

The [] operator of std::map returns a reference to the value associated with the given key. 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 in sorted order.

#include <iostream>
#include <map>
#include <string>

int main() 
{
    std::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 map in C++
    for (const auto& pair : wordFrequency) 
    {
        std::cout << pair.first << " :: " << pair.second << std::endl;
    }
    return 0;
}

Output:

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

In this snippet, wordFrequency[“Why”] = 1 inserts a new element with this key and sets its value to 1. The second line, wordFrequency[“Why”] = 2, updates the value associated with “Why” to 2. The elements are displayed in a sorted order based on their keys.

Using the at() Method

The at() function of std::map accepts a key and returns a reference to the value associated with the given key, with bounds checking. It throws a std::out_of_range exception if the key does not exist. This method ensures that the key already exists in the map.

#include <iostream>
#include <map>
#include <string>

int main()
{
    std::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 map in C++
    for (const auto &pair : wordFrequency)
    {
        std::cout << pair.first << " :: " << pair.second << std::endl;
    }
    return 0;
}

Output:

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

Using the find() Method

The find() function in std::map accepts a key as an argument and returns an iterator to the found element or to the end of the map if the key does not exist. We can use the find() function to fetch the iterator pointing to the given key and then use this iterator to change the value of the key-value pair.

#include <iostream>
#include <map>
#include <string>

int main()
{
    std::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 map in C++
    for (const auto &pair : wordFrequency)


    {
        std::cout << pair.first << " :: " << pair.second << std::endl;
    }
    return 0;
}

Output:

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

Summary

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