![]() |
VOOZH | about |
In C++, std::map::erase() is a built-in function of std::map container that is used to remove elements from the map using their key or iterator. We can also remove multiple elements using iterators. In this article, we will learn how to use the map::erase() in C++
The std::string::erase() function provides 6 different overloads for different purposes:
mp.erase(key); // For single element using key
mp.erase(pos); // For single element using iterator
mp.erase(first, last); // For multiple elements
The following are the different ways we can erase an element from std::map using map::erase() function:
We can remove a specific key-value pair from the map by passing its key to the map::erase() function.
mp.erase(key);
Parameter
Return Value
1: one 4: four
Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: O(1)
We can use the map::erase() function for deleting an element at the given position.
mp.erase(pos)
Parameters
Return Value
1: one 4: four
Time Complexity: O(1)
Auxiliary Space: O(1)
The map::erase() function also allows removing multiple elements from the map by specifying a range using iterators.
mp.erase(first, last)
Parameters
Return Value
1: one
Time Complexity: O(k + log n), where k is the number of elements in the range to be deleted and n is the number of elements in the map.
Auxiliary Space: O(1)