Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move contruct `std::map` from a different container

I want to convert a temporary container to a std::map<S, T>.

Let's say the temporary container is a std::unordered_map<S, T>, with T move-constructible.

My question is: (how) can I use move contructor of std::map<S, T>?

For a simplified case, consider

#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;
}

The output is

3 : 4
5 : 6
7 : 8

Of course, in a more complex setting, S and T are not int.

Thank you very much.

Update Thank you all for instant and valuable replies! I appreciate the observation that map is intrinsically different in data structure from an unordered_map. So if move cannot happen at the container level, I would also accept move at the element level. Just want to make sure and know how.

like image 915
aafulei Avatar asked Dec 07 '22 13:12

aafulei


1 Answers

Let's say the temporary container is a std::unordered_map, with T move-constructible.

If you wish to move your values whose type is movable T, instead of copy-ing, try using std::move_iterator as follows:

map<S, T> m(std::make_move_iterator(u.begin()), std::make_move_iterator(u.end()));

Example

#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()));
}

Output

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)
like image 183
Dean Seo Avatar answered Jan 05 '23 02:01

Dean Seo