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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With