c++ - 将 unique_ptr 的 unordered_map move 到另一个

标签 c++ c++11 move unordered-map unique-ptr

我正在尝试将 unique_ptr 的 unordered_map move 到另一个映射中,但出现以下编译错误。

#include <memory>
#include <unordered_map>
#include <string>

int main()
{
    std::unordered_map<int, std::unique_ptr<int>> aMap;
    std::unordered_map<int, std::unique_ptr<int>> bMap;

    std::unique_ptr<int> ptr(new int);
    *ptr = 10;
    aMap.insert(std::make_pair(0, std::move(ptr)));

    std::move(aMap.begin(), aMap.end(), bMap.end());


    return 0;
}


1>------ Build started: Project: Testing, Configuration: Debug Win32 ------
1>Build started 08.07.2012 23:54:16.
1>InitializeBuildStatus:
1>  Creating "Debug\Testing.unsuccessfulbuild" because "AlwaysCreate" was specified.
1>ClCompile:
1>  main.cpp
1>d:\progs\visual studio 2010\vc\include\utility(260): error C2166: l-value specifies const object
1>          d:\progs\visual studio 2010\vc\include\utility(259) : while compiling     class template member function 'std::pair<_Ty1,_Ty2> &std::pair<_Ty1,_Ty2>::operator =(std::pair<_Ty1,_Ty2> &&)'
1>          with
1>          [
1>              _Ty1=const int,
1>              _Ty2=std::unique_ptr<int>
1>          ]
1>          d:\coding\testing\main.cpp(12) : see reference to class template instantiation 'std::pair<_Ty1,_Ty2>' being compiled
1>          with
1>          [
1>              _Ty1=const int,
1>              _Ty2=std::unique_ptr<int>
1>          ]
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.64
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

最佳答案

我认为这是一个无法将元素添加到 map 或通过复制到末尾进行设置的问题。一个更简单的例子可以说明这一点

std::set<int> aSet;
std::set<int> bSet;
aSet.insert(0);

std::move(aSet.begin(), aSet.end(), bSet.end());

要解决这个问题,您需要一个 insert_iterator,所以

std::move(aSet.begin(), aSet.end(), inserter(bSet, bSet.begin()));

std::move(aMap.begin(), aMap.end(), inserter(bMap, bMap.begin()));

在内部,插入迭代器将尝试在传入的容器中调用“插入”,因此它不会尝试执行“*(bMap.end()) = *(aMap.begin())”,而是调用'bMap.insert(pos, *(aMap.begin()))',虽然 pos 对于这种情况并不是特别重要。

关于c++ - 将 unique_ptr 的 unordered_map move 到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11387272/

相关文章:

c++ - 数组平均程序输出错误

c++ - 在 C++ 中使用递归构建字符串

Python启动程序: Moving files

c++ - 如何检测 unordered_map vector 中的重复项?

c++ - 将其 move 到 map 后访问一对

ios - 如何在 iOS 上用用户手指平滑 move UIView

visual-studio-2013 - move 文件在 TFS 2013 中丢失历史记录

c++ - MySQL C++ 连接器始终输出相同的字符串

c++ - Windows 套接字 WSACleanup C++

c++ - 如何从第一个参数推导出第二个参数类型?