How to Replace a Key-Value Pair in a Map in C++?
Last Updated :
29 Feb, 2024
A map in C++ is a part of the Standard Template Library (STL) that allows the user to store data in key-value pairs where each key in a map must be unique. In this article, we will learn how to replace a specific key-value pair in a Map in C++.
Example:
Input :
map<int, string> mp={{1,"John"}, {2,"Bob"}, {3,"Alice"}};
keytoReplace = 3;
valuetoReplace = "Sam";
Output:
Original Map:
{1: John} {2: Bob} {3: Alice}
Updated Map:
{1: John} {2: Bob} {3: Sam}
Replace a Key-Value Pair in a Map in C++
To replace a specific key-value pair in a map in C++, we can use the array subscript [] operator to access the value associated with the specific key and then directly replace that key in the map using assignment operator.
C++ Program to Replace a Key-Value Pair in a Map in C++
The below example demonstrates how we can replace a specific key-value pair in a map in C++.
C++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map< int , string> mp
= { { 1, "John" }, { 2, "Bob" }, { 3, "Alice" } };
cout << "Original Map:" << endl;
for ( auto pair : mp) {
cout << "{" << pair.first << ": " << pair.second
<< "} " ;
}
cout << endl;
int keyToReplace = 3;
mp[keyToReplace] = "Sam" ;
cout << "Updated Map: " << endl;
for ( auto pair : mp) {
cout << "{" << pair.first << ": " << pair.second
<< "} " ;
}
return 0;
}
|
Output
Original Map:
{1: John} {2: Bob} {3: Alice}
Updated Map:
{1: John} {2: Bob} {3: Sam}
Time Complexity: O(logN), where N is the size of the map
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...