How to Remove a Key-Value Pair from Map in C++?
Last Updated :
04 Mar, 2024
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++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map< int , int > myMap = { { 1, 10 },
{ 3, 30 },
{ 2, 20 },
{ 4, 40 },
{ 5, 50 } };
int keyToRemove = 4;
auto it = myMap.find(keyToRemove);
if (it != myMap.end()) {
myMap.erase(it);
}
else {
cout << "Key " << keyToRemove
<< " not found in the map." << endl;
}
cout << "Map After Removal:" << endl;
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)
Share your thoughts in the comments
Please Login to comment...