VOOZH about

URL: https://www.geeksforgeeks.org/cpp/map-erase-function-in-c-stl/

⇱ map erase() Function in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

map erase() Function in C++ STL

Last Updated : 11 Jul, 2025

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++

Syntax

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:

Erase an Element by Key

We can remove a specific key-value pair from the map by passing its key to the map::erase() function.

Syntax

mp.erase(key);

Parameter

  • key: The key of the element to delete.

Return Value

  • Returns the number of elements to be removed. For a map, it will either return 1 or 0.

Example


Output
1: one
4: four

Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: O(1)

Erase an Element by Iterator

We can use the map::erase() function for deleting an element at the given position.

Syntax

mp.erase(pos)

Parameters

  • pos: Iterator to the element to delete.

Return Value

  • Returns an iterator to the next element after the removed range.

Example


Output
1: one
4: four

Time Complexity: O(1)
Auxiliary Space: O(1)

Erase a Range of Elements

The map::erase() function also allows removing multiple elements from the map by specifying a range using iterators.

Syntax

mp.erase(first, last)

Parameters

  • first: Iterator pointing to the starting position of the range.
  • last: Iterator pointing to the element just after the last element of the range.

Return Value

  • Returns an iterator to the next element after the removed range.

Example


Output
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)

Comment