How to Update Value of a Key in Map in C++?
Last Updated :
09 Feb, 2024
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++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map< int , string> myMap = { { 1, "One" }, { 2, "Two" } };
myMap[2] = "Three" ;
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)
Share your thoughts in the comments
Please Login to comment...