Reputation: 42168
I have a map<std::string, std::unique_ptr<Cls>> my_map
. I would like to move out some value from this map, to have the following:
std::unique_ptr<Cls> cls = my_map.get_and_erase("some str");
erase
doesn't return a value unfortunately. What is my best approach here?
Upvotes: 2
Views: 2396
Reputation: 117298
Since C++17 you have std::map::extract
:
// if the key exists in the map, it'll be deleted after this:
auto cls_node = my_map.extract("some str");
if(not cls_node.empty()) // cls_node.mapped() gives access to the mapped value
Upvotes: 6
Reputation: 238311
You can use the following algorithm:
find
to get an iterator to the element.Upvotes: 5