Open In App

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

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

In C++, maps are used to store key-value pairs in which each key is unique. In this article, we will learn how to delete a key-value pair from a map in C++.

Example

Input: 
mp={ {1,"One"}, {2,"Two"},{3,"Three"}}
Key= 2

Output:
Map after deleting key:
1: One
3: Three

Remove a Key-Value Pair from Map in C++

To delete a key-value pair from a map, we can use the std::map::erase() method. First, we will check if a key for a key-value pair that you want to delete exists or not. If it exists, we then remove it by simply passing the key to the erase() function.

C++ Program to Delete Key-Value Pair from Map

C++




// C++ program to delete the key-value pair from a map
#include <iostream>
#include <map>
  
using namespace std;
  
int main()
{
    // Creating a map
    map<int, string> myMap;
  
    // Inserting key-value pairs into the map
    myMap[1] = "One";
    myMap[2] = "Two";
    myMap[3] = "Three";
  
    // Displaying the map before deletion
    cout << "Map before deletion:" << endl;
    for (const auto& pair : myMap) {
        cout << pair.first << ": " << pair.second << endl;
    }
  
    // Finding the iterator for the key to be deleted
    int key = 2;
    auto it = myMap.find(key);
  
    // Deleting the key-value pair using erase()
    if (it != myMap.end()) {
        myMap.erase(it);
    }
  
    // Displaying the map after deletion
    cout << "\nMap after deletion:" << endl;
    for (const auto& pair : myMap) {
        cout << pair.first << ": " << pair.second << endl;
    }
  
    return 0;
}


Output

Map before deletion:
1: One
2: Two
3: Three

Map after deletion:
1: One
3: Three

Time Complexity: O(log N)
Space Complexity: O(1)

Note: We can also use clear() function to delete key-value pair from a map.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads