Open In App

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

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a map is an associative container that stores elements in key-value pairs, where the key values are unique. In this article, we will learn how to remove a specific key-value pair from a map in C++.

Example:

Input : 
myMap = {{1, 10}, {3, 30}, {2, 20}, {4, 40}};
key = 2

Output :
Map After Removal:
1: 10
3: 30
4: 40

Remove a Key from a Map in C++

To remove a specific key-value pair from a std::map, we can use the std::map::erase function. This function removes the key-value pair associated with the given key from the map.

C++ Program to Remove a Key-Value Pair from Map

The below program demonstrates how we can remove a specific key-value pair from a map in C++ STL.

C++




// C++ Program to illustrate how to Remove a Specific
// Key-Value Pair from a Map
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Create a map with integer keys and values
    map<int, int> myMap = { { 1, 10 },
                            { 3, 30 },
                            { 2, 20 },
                            { 4, 40 },
                            { 5, 50 } };
  
    // Specify the key you want to remove
    int keyToRemove = 4;
  
    // Find the iterator for the specified key
    auto it = myMap.find(keyToRemove);
  
    // Check if the key is found
    if (it != myMap.end()) {
        // Erase the key-value pair from the map
        myMap.erase(it);
    }
    else {
        // Output if the key is not found
        cout << "Key " << keyToRemove
             << " not found in the map." << endl;
    }
    cout << "Map After Removal:" << endl;
    // Print the updated map
    for (const auto& pair : myMap) {
        cout << pair.first << ": " << pair.second << endl;
    }
  
    return 0;
}


Output

Map After Removal:
1: 10
2: 20
3: 30
5: 50

Time Complexity: O(log N), here N is the number of elements in the map
Space Complexity: O(1)



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

Similar Reads