![]() |
VOOZH | about |
in C++, std::unordered_map::erase() is a built-in function used remove elements from the unordered_map container. It is a member function of std::unordered_map class defined inside <unordered_map> header file.
Example:
2: Geeksfor 1: Geeks
C++ provides 3 implementations of the std::unordered_map::erase() method:
um.erase(k); // Erases by key
um.erase(it); // Erases by iterator
um.erase(first, last); // Erases range of elements
These implementations can be used to do erase the elements in the following ways:
With the help of std::unordered_map::erase() function, we can erase the specified key from the std::unordered_map container.
um.erase(k);
Parameters
Return Value
1: Geeks 3: GeeksforGeeks
Time Complexity: O(1) in average case, O(n) in worst case, where n is the number of elements in the unordered_map.
Auxiliary Space: O(1)
We can also use unordered_map::erase() to delete an element at a specific position using an iterator. This method is useful when we are iterating the map and removing the elements based on some given conditions.
um.erase(it);
Parameters
Return Value
2: Geeksfor 3: GeeksforGeeks
Time Complexity: O(1)
Auxiliary Space: O(1)
We can also remove a sequence of elements in one operation using std::unordered_map::erase() method by defining the range using iterators.
um.erase(first, last);
Parameters
Return Value
2: Geeksfor
Time Complexity: O(k) in average case, where k is number of elements between first and last, O(n) in worst case, where n is the number of elements in unordered_map.
Auxiliary Space: O(1)