How to Delete a Key-Value Pair from a Map in C++?
Last Updated :
06 Feb, 2024
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++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map< int , string> myMap;
myMap[1] = "One" ;
myMap[2] = "Two" ;
myMap[3] = "Three" ;
cout << "Map before deletion:" << endl;
for ( const auto & pair : myMap) {
cout << pair.first << ": " << pair.second << endl;
}
int key = 2;
auto it = myMap.find(key);
if (it != myMap.end()) {
myMap.erase(it);
}
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.
Share your thoughts in the comments
Please Login to comment...