C++ unordered_map erase() Function
Example
Remove the element with the key "John":
unordered_map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
cout << "Before: " << people.size() << "\n";
people.erase("John");
cout << "After: " << people.size();
Definition and Usage
The erase() function removes one or more elements from an unordered map.
You can remove an element by its key, or by an iterator that points to it. You can also remove all elements between two iterators.
The erase function is defined in the <unordered_map> header file.
Tip: Use clear() to remove all elements.
Syntax
unordered_map.erase(keyType key)
unordered_map.erase(iterator position)
unordered_map.erase(iterator start, iterator end)
Use one of the three forms above. keyType is the type of the keys in the unordered map, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| key | Required. The key of the element to remove. |
| position | Required. An iterator pointing to the element to remove. |
| start | Required. An iterator pointing to the first element to remove. |
| end | Required. An iterator pointing to the position after the last element to remove. The element at this position is not removed. |
Technical Details
| Returns: | When you remove by key: the number of elements removed (1 or 0). When you remove by iterator: an iterator to the element after the last removed element. |
|---|
Related Pages
Read more about unordered maps in our Unordered Map Tutorial.