使用map :: insert复制unique_ptr的映射

时间:2015-11-30 00:09:23

标签: c++ stdmap

是否有可能使用std::map::insertstd::copystd::map std::unique_ptr深层复制到另一个?{/ p>

我有以下内容:

class MyObject {}

std::map<int32_t, std::unique_ptr<MyObject>> entries1;

// Populate entries1
// ...

std::map<int32_t, std::unique_ptr<MyObject>> entries2;

entries2.insert(entries1.begin(), entries1.end());

显然,使用简单的插入不起作用,因为std::unique_ptr是不可复制的:

  

尝试引用已删除的功能

在这个答案How can I copy one map into another using std::copy?中,自定义插入器与std::copy一起被提取,但我真的不知道如何在我的上下文中使用它。

手动实现(在循环中迭代和复制每个对象)是唯一的解决方案吗? E.g:

for (const auto &entry : entries1)
{
    entries2.insert({ entry.first, std::make_unique<MyObject>(*entry.second) });
}

0 个答案:

没有答案
相关问题