How to Delete a Pair from an Unordered Map in C++?
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++
// C++ program to delete pair from unordered map #include <iostream> #include <unordered_map> using namespace std; int main() { // Create an unordered_map unordered_map< int , string> myUnorderedMap; // Insert some elements myUnorderedMap[1] = "Apple" ; myUnorderedMap[3] = "Mango" ; myUnorderedMap[2] = "Orange" ; // Find the iterator for key int key = 3; auto iter = myUnorderedMap.find(key); // Delete the pair with key if found if (iter != myUnorderedMap.end()) { myUnorderedMap.erase(iter); } // Display elements after deletion 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.