emplace

std::map emplace without copying value

北慕城南 提交于 2019-11-27 00:36:55
The C++11 std::map<K,V> type has an emplace function, as do many other containers. std::map<int,std::string> m; std::string val {"hello"}; m.emplace(1, val); This code works as advertised, emplacing the std::pair<K,V> directly, however it results in a copy of key and val taking place. Is it possible to emplace the value type directly into the map as well? Can we do better than moving the arguments in the call to emplace ? Here's a more thorough example: struct Foo { Foo(double d, string s) {} Foo(const Foo&) = delete; Foo(Foo&&) = delete; } map<int,Foo> m; m.emplace(1, 2.3, string("hello")); /

insert vs emplace vs operator[] in c++ map

扶醉桌前 提交于 2019-11-26 23:26:32
I'm using maps for the first time and I realized that there are many ways to insert an element. You can use emplace() , operator[] or insert() , plus variants like using value_type or make_pair . While there is a lot of information about all of them and questions about particular cases, I still can't understand the big picture. So, my two questions are: What is the advantage of each one of them over the others? Was there any need for adding emplace to the standard? Is there anything that wasn't possible before without it? In the particular case of a map the old options were only two: operator[

std::map emplace without copying value

无人久伴 提交于 2019-11-26 12:24:30
问题 The C++11 std::map<K,V> type has an emplace function, as do many other containers. std::map<int,std::string> m; std::string val {\"hello\"}; m.emplace(1, val); This code works as advertised, emplacing the std::pair<K,V> directly, however it results in a copy of key and val taking place. Is it possible to emplace the value type directly into the map as well? Can we do better than moving the arguments in the call to emplace ? Here\'s a more thorough example: struct Foo { Foo(double d, string s)