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.