Change the Value of a Key in Map in C++

To update the value of a key in the map, we can use the subscript operator [] to directly access and assign value. The key will be passed inside the [] and the assignment operator will be used to assign the new value. Keep in mind that the new value should be of the same type as the previous one.

C++ Program to Update Value of a Key in Map

C++




// C++ Program to Update Value of a Key in Map
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
  
    // creating a map
    map<int, string> myMap = { { 1, "One" }, { 2, "Two" } };
  
    // Updating an existing element's value
    myMap[2] = "Three";
  
    // Accessing and printing elements
    cout << "Map after Updating" << endl;
    for (auto it : myMap) {
        cout << "Key:" << it.first << " Value:" << it.second
             << endl;
    }
  
    return 0;
}


Output

Map after Updating
Key:1 Value:One
Key:2 Value:Three

Time Complexity: O(1)
Auxiliary Space: O(1)


How to Update Value of a Key in Map in C++?

In C++, a map is a data structure that stores key-value pairs. In this article, we will learn how to change the value of a key that is already present in the map container in C++.

Example

Input:
map<int, string> mp = {(1, "One"), (2,"Two")}

Output: 
map after Updation: {(1, "One"), (2, "Three")}

Similar Reads

Change the Value of a Key in Map in C++

To update the value of a key in the map, we can use the subscript operator [] to directly access and assign value. The key will be passed inside the [] and the assignment operator will be used to assign the new value. Keep in mind that the new value should be of the same type as the previous one....

Contact Us