Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert map entry by r-value moving of mapped_type

I have a map with a (fairly) simple key-type and a complex mapped-type, like so:

map<string, vector<string>> myMap;

If I have a vector<string> in hand, is it possible to insert an entry into the map which copies the key but moves the mapped-value? That is, is there some way to do:

string key = "Key";
vector<string> mapped;
for (int i = 0; i < 1000; ++i)
  mapped.push_back("Some dynamic string");

// Insert by moving mapped; I know I'm done with it
myMap.insert(make_pair(key, move(mapped))); // This seems to move key too
like image 294
Chowlett Avatar asked Jan 29 '13 11:01

Chowlett


1 Answers

You are looking for std::map::emplace:

myMap.emplace(key, move(mapped));

this calls the appropiate std::pair constructor in-place:

template< class U1, class U2 >
pair( U1&& x, U2&& y );

Since the first argument is an l-value, the key gets copied, but the second (mapped) is an rvalue and thus gets move-constructed.

like image 101
Arne Mertz Avatar answered Oct 29 '22 22:10

Arne Mertz