Remove a key from a map in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <map> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'D'} }; int key = 4; auto it = map.find(key); if (it != map.end()) { map.erase(it); } for (const auto &entry: map) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'D'} }; int key = 4; map.erase(key); for (const auto &entry: map) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
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++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)