Insert map entry by r-value moving of mapped_type

99封情书 提交于 2019-12-04 17:37:26

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/14581414/insert-map-entry-by-r-value-moving-of-mapped-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!