C++ std::unordered_map erase() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::unordered_map

Definition

In C++, std::unordered_map::erase() removes pairs from a std::unordered_map. You can name the key to remove, give an iterator to one pair, or give a range of iterators.

The unordered_map stays valid after the erase. Erasing a key that is not in the unordered_map is safe and simply removes nothing. Include <unordered_map> to use it.

This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.

Syntax

Pass a key, one iterator, or a pair of iterators.

C++
std::size_t n = m.erase("b");        // remove by key (0 or 1)
m.erase(m.find("c"));                // remove one pair by iterator
auto next = m.erase(it);             // returns the next iterator
m.erase(m.begin(), m.end());         // remove a range (here: all)
CallWhat it does
m.erase(key)Removes the pair with that key. Returns the number of pairs removed: 0 or 1.
m.erase(pos)Removes the pair that pos points to. Returns an iterator to the next pair.
m.erase(first, last)Removes every pair in the range [first, last). Returns last.

erase(pos) must get a valid dereferenceable iterator. m.erase(m.find(k)) is a bug when k is missing, because find() then returns end().

Library declarations
C++
iterator erase(iterator pos);
iterator erase(const_iterator pos);
iterator erase(const_iterator first, const_iterator last);
size_type erase(const Key& key);

Parameters

ParameterDescription
keyThe key of the pair to remove.
posAn iterator to the pair to remove. It must not be end().
first, lastThe range of pairs to remove. last itself is not removed.

Return Value

Return ValueDescription
size_typeFor the key form: how many pairs were removed. For an unordered_map this is 0 or 1.
iteratorFor the iterator forms: the pair that followed the last removed one, or end().

C++ Examples

Example 1 — erase() by Key

Remove a key that exists and a key that does not, and print the returned count.

C++
#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};

    std::size_t n1 = m.erase("b");
    std::size_t n2 = m.erase("zzz");

    std::cout << "removed: " << n1 << '\n';
    std::cout << "removed: " << n2 << '\n';

    for (const auto& kv : m) {
        std::cout << kv.first << ' ';
    }
    std::cout << '\n';
    return 0;
}

How It Works

  1. m.erase("b") finds the key, removes its pair, and returns 1.
  2. m.erase("zzz") does not find the key. That is not an error: it removes nothing and returns 0.
  3. Only a and c are left, and they are printed in key order.

Example 2 — erase() with an Iterator and a Range

Erase one pair that find() located, then erase everything from one key to the end.

C++
#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<int, std::string> m = {
        {1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}, {5, "five"}
    };

    auto it = m.find(2);
    if (it != m.end()) {
        m.erase(it);                      // remove the pair for key 2
    }

    m.erase(m.find(4), m.end());          // remove key 4 and everything after it

    for (const auto& kv : m) {
        std::cout << kv.first << "=" << kv.second << ' ';
    }
    std::cout << '\n';
    return 0;
}

How It Works

  1. find(2) returns an iterator to the pair for key 2. The if makes sure it is not end(), and erase(it) removes that pair.
  2. erase(m.find(4), m.end()) removes the range that starts at key 4 and runs to the end, so keys 4 and 5 go.
  3. The pairs for keys 1 and 3 remain, so the output is 1=one 3=three.

Example 3 — erase() Inside a Loop

Remove every pair with an odd value while walking the unordered_map. The loop uses the iterator that erase() returns.

C++
#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}, {"d", 4}};

    for (auto it = m.begin(); it != m.end(); ) {
        if (it->second % 2 != 0) {
            it = m.erase(it);     // erase returns the next iterator
        } else {
            ++it;
        }
    }

    for (const auto& kv : m) {
        std::cout << kv.first << "=" << kv.second << ' ';
    }
    std::cout << '\n';
    return 0;
}

How It Works

  1. The for has no ++it in its header, because the loop body decides how to move on.
  2. For an odd value, it = m.erase(it) removes the pair and stores the iterator to the next pair in it. For an even value, the loop moves on with ++it.
  3. a=1 and c=3 are removed, so the unordered_map holds b=2 and d=4.

Frequently Asked Questions

It removes pairs from the unordered_map, either one by key, one by iterator, or a whole range of iterators.
Nothing happens, and erase(key) returns 0. It is safe.
The number of pairs removed. Because map keys are unique, that is always 0 or 1.
Use it = m.erase(it) when you erase, and ++it when you do not. erase() returns the iterator to the next pair, so the loop never uses an invalid iterator.
No. Only iterators and references to the erased pairs become invalid. The rest of the unordered_map is untouched.

Next: extract()

Keep going through the std::unordered_map functions. Take a pair out of the unordered_map as a node handle (C++17).

extract() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful