Open In App

How to Replace a Key-Value Pair in a Map in C++?

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

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++




// C++ Program to illustrate how to Replace a Specific
// Key-Value Pair in a Map
#include <iostream>
#include <map>
using namespace std;
int main()
{
    // creating and Initializing a map
    map<int, string> mp
        = { { 1, "John" }, { 2, "Bob" }, { 3, "Alice" } };
  
    // Print the original map
    cout << "Original Map:" << endl;
    for (auto pair : mp) {
        cout << "{" << pair.first << ": " << pair.second
             << "} ";
    }
    cout << endl;
    // Replace key value pairs in the map
    int keyToReplace = 3;
    mp[keyToReplace] = "Sam";
  
    cout << "Updated Map: " << endl;
  
    // Print the updated map
    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)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads