問題描述
C++11 std::map<K,V>
類型有一個 emplace
函數,許多其他容器也是如此.
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);
此代碼如宣傳的那樣工作,直接替換 std::pair
,但它會生成 key
和 val<的副本/code> 正在發(fā)生.
This code works as advertised, emplacing the std::pair<K,V>
directly, however it results in a copy of key
and val
taking place.
是否也可以將值類型直接嵌入到地圖中?我們能比將調用中的參數移動到 emplace
做得更好嗎?
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")); // invalid
推薦答案
你傳遞給 map::emplace
的參數會被轉發(fā)給 map::value_type
的構造函數, 即 pair
.所以你可以使用 std::pair
的 分段構造構造函數避免中間復制和移動.
The arguments you pass to map::emplace
get forwarded to the constructor of map::value_type
, which is pair<const Key, Value>
. So you can use the piecewise construction constructor of std::pair
to avoid intermediate copies and moves.
std::map<int, Foo> m;
m.emplace(std::piecewise_construct,
std::forward_as_tuple(1),
std::forward_as_tuple(2.3, "hello"));
現場演示
這篇關于std::map emplace 不復制值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!