gruszczy
gruszczy

Reputation: 42168

Find and remove unique_ptr from a map

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

Answers (2)

Ted Lyngmo
Ted Lyngmo

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

eerorika
eerorika

Reputation: 238311

You can use the following algorithm:

  • Use find to get an iterator to the element.
  • Move from the element.
  • Erase using the iterator.

Upvotes: 5

Related Questions