【问题标题】:How move map to other map如何将地图移动到其他地图
【发布时间】:2017-04-14 21:48:14
【问题描述】:
std::map<long long, std::unique_ptr<A>> listOf1;
std::map<long long, std::unique_ptr<A>> listOf2;

如何将 listOf1 添加到 listOf2? 可能这很棘手,因为 value 是 unique_ptr。 正常解决方案:

listOf2.insert(listOf1.begin(), listOf1.end());

不起作用并给出错误

严重性代码描述项目文件行源抑制状态 错误 C2280 'std::pair::pair(const std::pair &)': 试图引用已删除的函数 c:\program files (x86)\microsoft visual studio 14.0\vc\include\xmemory0 737 Build

【问题讨论】:

  • “移动”是什么意思?你想要移动分配吗?是否要将一个映射中的所有条目添加到另一个映射(并从第一个映射中删除它们)?
  • 类似:listOf2.insert(std::make_move_iterator(listOf1.begin()), std::make_move_iterator(listOf1.end()));?
  • 我想将第一张地图的所有元素添加到第二张地图并删除第一张地图。
  • @Jarod42 谢谢,这是我的问题的答案:)
  • @KerrekSB 你在意什么?

标签: c++ algorithm c++11


【解决方案1】:

你可能想要:

listOf2.insert(std::make_move_iterator(listOf1.begin()),
               std::make_move_iterator(listOf1.end()));
listOf1.clear();

【讨论】:

    【解决方案2】:

    如果您有实现 C++17 node handle 接口的标准库实现,则可以使用 map::merge 函数将节点从一个 map 拼接到另一个。

    map::insert 相比这样做的好处是,地图不会移动构造元素,而是通过简单地复制一些内部指针来转移节点的所有权。

    #include <map>
    #include <iostream>
    #include <memory>
    
    struct A
    {};
    
    int main()
    {
        std::map<long long, std::unique_ptr<A>> listOf1;
        std::map<long long, std::unique_ptr<A>> listOf2;
    
        listOf1[10] = std::make_unique<A>();
        listOf1[20] = std::make_unique<A>();
        listOf1[30] = std::make_unique<A>();
        listOf2[30] = std::make_unique<A>();
        listOf2[40] = std::make_unique<A>();
    
        listOf1.merge(listOf2);
        for(auto const& m : listOf1) std::cout << m.first << '\n';
    }
    

    Live demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多