How to Delete a Pair from an Unordered Map in C++?
Last Updated :
06 Feb, 2024
In C++, the unordered_map is like a dictionary that stores data in the form of key-value pairs. In this article, we will learn how to delete a key-value pair from an unordered_map in C++.
Example
Input:
mp={ {1,"Apple"}, {3,"Mango"},{2,"Orange"}}
Key= 3
Output:
Map after deleting key:
1: Apple
2: Orange
Remove Key-Value Pair from Unordered Map in C++
In unordered_map, we can delete a pair by using the std::unordered_map::erase() method. First, we check if a key for a pair that you want to delete exists or not. If it exists, then we remove it by simply passing that key to the erase() function.
C++ Program to Delete a Pair from Unordered Map
C++
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map< int , string> myUnorderedMap;
myUnorderedMap[1] = "Apple" ;
myUnorderedMap[3] = "Mango" ;
myUnorderedMap[2] = "Orange" ;
int key = 3;
auto iter = myUnorderedMap.find(key);
if (iter != myUnorderedMap.end()) {
myUnorderedMap.erase(iter);
}
cout << "\nUnordered Map after deletion:" << endl;
for ( const auto & pair : myUnorderedMap) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
|
Output
Unordered Map after deletion:
2: Orange
1: Apple
Time Complexity: O(N) is worst case time complexity, while the average complexity is O(1).
Auxiliary Space: O(1)
Note: We can also use clear() function to delete key-value pair from a unordered map.
Share your thoughts in the comments
Please Login to comment...