In this shot, we will learn how to use the unordered_map::erase()
function in C++.
The unordered_map::erase()
removes some particular key-value pairs from the map. It has three variations:
Specifying the iterator: In this case, the function accepts only one parameter, i.e., the iterator, which points to the key-value pair to be erased.
Specifying the range: In this case, the function accepts two parameters:
#include <iostream>#include <unordered_map>using namespace std;int main(){unordered_map<int,string> umap ={{12, "unordered"},{16, "map"},{89, "in"},{66, "C++"}};cout << "After erasing by iterator : \n";umap.erase(umap.begin());for (auto p : umap)cout << p.first << "->" << p.second << endl;cout << "After erasing by key : \n";umap.erase(16);for (auto p : umap)cout << p.first << "->" << p.second << endl;cout << "After erasing by range : \n";auto i = umap.begin();i++;umap.erase(i, umap.end());for (auto p : umap)cout << p.first << "->" << p.second << endl;return 0;}
This is how we use the unordered_map::erase()
function in C++ to remove some particular key-value pairs from the map.