unordered_map erase in C++ STL

erase function is used to erase elements from the unordered_map. There are three type of erase functions supported by unordered_map :

  1. erasing by iterator: It takes an iterator as a parameter and erases the key and value present at that iterator.
    Syntax

    unordered_map.erase(const iterator);
  2. erasing by key: It takes a key as a parameter and erases the key and value.
    Syntax



    unordered_map.erase(const key);
  3. erase by range: It takes two iterators as a parameter and erases all the key and values present in between (including the starting iterator and excluding the end iterator).
    Syntax:

    unordered_map.erase(const iteratorStart, const iteratorEnd);
filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to demonstrate implementation of
// erase function in unordered_map.
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    unordered_map<int, bool> um;
  
    // Adding some elements in the map.
    um[12] = true;
    um[4189] = false;
    um[519] = true;
    um[40] = false;
    um[4991] = true;
  
    cout << "Contents of the unordered_map : \n";
    for (auto p : um)
        cout << p.first << "==>" << p.second << "\n";
    cout << "\n";
  
    // erase by iterator
    cout << "After erasing by Iterator : \n";
    um.erase(um.begin());
    for (auto p : um)
        cout << p.first << "==>" << p.second << "\n";
    cout << "\n";
  
    // erase by value
    cout << "After erasing by Key : \n";
    um.erase(4189);
    for (auto p : um)
        cout << p.first << "==>" << p.second << "\n";
    cout << "\n";
  
    // erase by range
    cout << "After erasing by Range : \n";
    auto it = um.begin();
    it++; // Returns iterator pointing to second element
    um.erase(it, um.end());
    for (auto p : um)
        cout << p.first << "==>" << p.second << "\n";
    cout << "\n";
  
    return 0;
}

chevron_right


Output:

Contents of the unordered_map :
4991==>1
519==>1
40==>0
12==>1
4189==>0

After erasing by Iterator :
519==>1
40==>0
12==>1
4189==>0

After erasing by Key :
519==>1
40==>0
12==>1

After erasing by Range :
519==>1
 



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.