简体   繁体   中英

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?

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.value() gives access to the value

You can use the following algorithm:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM