从另一个容器移动contruct`std :: map`

aaf*_*lei 4 c++ move-semantics

我想将一个临时容器转换为一个std::map<S, T>.

假设临时容器是一个std::unordered_map<S, T>T移动构造的容器.

我的问题是:(怎么样)我可以使用移动构造函数std::map<S, T>吗?

对于简化的案例,请考虑

#include <bits/stdc++.h>
using namespace std;

template<typename S, typename T>
map<S, T>
convert(unordered_map<S, T> u)
{
    // Question: (how) can I use move constructor here?
    map<S, T> m(u.begin(), u.end());
    return m;
}

int main()
{
    unordered_map<int, int> u;

    u[5] = 6;
    u[3] = 4;
    u[7] = 8;

    map<int, int> m = convert(u);

    for (auto kv : m)
        cout << kv.first << " : " << kv.second << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是

3 : 4
5 : 6
7 : 8
Run Code Online (Sandbox Code Playgroud)

当然,在一个更复杂的设置,ST不是int.

非常感谢你.

更新感谢大家的即时和有价值的回复!我很欣赏与map数据结构本质上不同的观察结果unordered_map.因此,如果移动不能在容器级别发生,我也会接受元素级别的移动.只是想确定并知道如何.

Dea*_*Seo 14

假设临时容器是std :: unordered_map,T move-constructible.

如果您希望移动类型可移动T,而不是复制,请尝试std::move_iterator按如下方式使用:

map<S, T> m(std::make_move_iterator(u.begin()), std::make_move_iterator(u.end()));
Run Code Online (Sandbox Code Playgroud)

#include <iostream>
#include <map>
#include <unordered_map>
#include <iterator>


struct S
{
    bool init = true;
    static int count;
    S() { std::cout << "S::S() " << ++count << "\n"; }
    S(S const&) { std::cout << "S::S(S const&)\n"; }
    S(S&& s) { std::cout << "S::S(S&&)\n"; s.init = false; }
    ~S() { std::cout << "S::~S() (init=" << init << ")\n"; }
};

int S::count;


int main()
{
    std::cout << "Building unordered map\n";
    std::unordered_map<int, S> um;
    for (int i = 0; i < 5; ++i)
        um.insert(std::make_pair(i, S()));

    std::cout << "Building ordered map\n";
    std::map<int, S> m(
        std::make_move_iterator(um.begin()), 
        std::make_move_iterator(um.end()));
}
Run Code Online (Sandbox Code Playgroud)

产量

Building unordered map
S::S() 1
S::S(S&&)
S::S(S&&)
S::~S() (init=0)
S::~S() (init=0)
S::S() 2
S::S(S&&)
S::S(S&&)
S::~S() (init=0)
S::~S() (init=0)
S::S() 3
S::S(S&&)
S::S(S&&)
S::~S() (init=0)
S::~S() (init=0)
S::S() 4
S::S(S&&)
S::S(S&&)
S::~S() (init=0)
S::~S() (init=0)
S::S() 5
S::S(S&&)
S::S(S&&)
S::~S() (init=0)
S::~S() (init=0)
Building ordered map
S::S(S&&)
S::S(S&&)
S::S(S&&)
S::S(S&&)
S::S(S&&)
S::~S() (init=1)
S::~S() (init=1)
S::~S() (init=1)
S::~S() (init=1)
S::~S() (init=1)
S::~S() (init=0)
S::~S() (init=0)
S::~S() (init=0)
S::~S() (init=0)
S::~S() (init=0)
Run Code Online (Sandbox Code Playgroud)