繁体   English   中英

从地图中查找并删除 unique_ptr

[英]Find and remove unique_ptr from a map

我有一个map<std::string, std::unique_ptr<Cls>> my_map 我想从这张地图中移出一些价值,以获得以下内容:

std::unique_ptr<Cls> cls = my_map.get_and_erase("some str");

不幸的是, erase不会返回值。 我在这里最好的方法是什么?

由于 C++17 你有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

您可以使用以下算法:

  • 使用find获取元素的迭代器。
  • 从元素移动。
  • 使用迭代器擦除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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