This post will discuss how to remove a key from a map in C++.

The standard approach to remove elements from a map is using the std::map::erase member function. It offers several overload versions. The first overload version accepts an iterator pointing to an element that needs to be removed from the map. We can get an iterator to a specific element using the std::map::find function and pass it to std::map::erase if found.

Download  Run Code

Output:

{1, A}
{2, B}
{3, C}

 
The std::map::erase function is also overloaded to accept the key of the element that needs to be removed from the map. This is a better solution than above, designed for ease of use and efficiency.

Download  Run Code

Output:

{1, A}
{2, B}
{3, C}

 
Note that it is not possible to conditionally remove elements from associative containers like std::map, using the std::remove_if function.

That’s all about removing a key from a map in C++.