【问题标题】:Find and remove unique_ptr from a map从地图中查找并删除 unique_ptr
【发布时间】:2020-03-22 01:35:57
【问题描述】:

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

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

erase 不幸的是没有返回值。我最好的方法是什么?

【问题讨论】:

    标签: c++ dictionary unique-ptr


    【解决方案1】:

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

    【讨论】:

    • 这很好!这是否适用于 unique_ptr,即它会将其移出?
    • @gruszczy 是的,它在你得到的节点中,所以auto cls = std::move(cls_node.value()); 会给你。作为奖励,如果您打算使用不同的密钥重新插入节点,您可以更改密钥:cls_node.key() = "new value"; my_map.insert(std::move(cls_node)); 这应该比旧方式更快的密钥更改(理论上 - 我从未测量过它)。
    • 非常感谢!我对此表示赞同,但我现在会接受另一个答案,因为它对早期的 C++ 版本很友好。有朝一日,这应该会成为公认的答案。
    • 似乎 mapped() 是获取从 std::map 中提取的节点值的正确函数。 value() 仅适用于“set”容器,而 .mapped() 是用于“map”容器的。见:en.cppreference.com/w/cpp/container/node_handle
    • @yfede 谢谢!我已经更正了!
    【解决方案2】:

    您可以使用以下算法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-17
      • 2021-12-24
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      相关资源
      最近更新 更多