Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an entry from a std::map using key?

I am having a following a map,

struct details;

map<std::string, details> myMap;

myMap.erase(“key”);// Why I cant do this in C++11?

This is so simple in java

Map<std::string, details> map
map.remove(“key");

How can I delete an entry from a std::map using key?

Thanks

like image 640
Kid Avatar asked Oct 16 '25 17:10

Kid


1 Answers

How to remove an entry from a std::map using key?

Call the erase member function on the std::map<Key> container using the erase(const Key& key) form just like had been shown:

myMap.erase("key");

Alternatively, go through the extra steps necessary for finding the entry and erasing by iterator. Here's an example of this:

const auto it = myMap.find("key");
if (it != myMap.end())
    myMap.erase(it);

As @FriskySaga points out in their comment, only call erase with the returned iterator if it's not the end() iterator.

Why I cant do this in C++11?

The container myMap has to be modifiable. I.e. it cannot be marked const. Otherwise, you'll get a compiler error.

In the Feb 14, 2017 comment, @Kid shared that std::map<std::string, incident_information> const incidentDetails was the actual map they were using. @Quentin rightly recognizes in their response comment that this map - that is const - can't be modified. Trying to use erase results in a compiler error as @Kid realizes in their follow up comment.

like image 70
Louis Langholtz Avatar answered Oct 18 '25 21:10

Louis Langholtz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!