VOOZH about

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

⇱ unordered_map erase in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

unordered_map erase in C++ STL

Last Updated : 11 Jul, 2025

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:


Output
2: Geeksfor
1: Geeks

unordered_map::erase() Syntax

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:

Erase an Element by Key

With the help of std::unordered_map::erase() function, we can erase the specified key from the std::unordered_map container.

Syntax

um.erase(k);

Parameters

  • k: Key of the element to be removed.

Return Value

  • Returns the number of elements removed from the std::unordered_map container. Can only be 0 or 1.

Example


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

Erase an Element by Iterator

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.

Syntax

um.erase(it);

Parameters

  • it: Iterator to the element to be removed.

Return Value

  • Returns an iterator point to the element that is just after the removed element.
  • If there is no such element, returns iterator to unordered_map::end().

Example


Output
2: Geeksfor
3: GeeksforGeeks

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

Erase a Range of Elements

We can also remove a sequence of elements in one operation using std::unordered_map::erase() method by defining the range using iterators.

Syntax

um.erase(first, last);

Parameters

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

Return Value

  • Returns an iterator point to the element that is just after the removed range.
  • If there is no such element, returns iterator to unordered_map::end().

Example


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


Comment