Kid
Kid

Reputation: 179

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

Upvotes: 4

Views: 10559

Answers (1)

Louis Langholtz
Louis Langholtz

Reputation: 3123

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.

Upvotes: 5

Related Questions