Open In App

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

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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")}

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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads