std :: map emplace没有复制值 [英] std::map emplace without copying value
问题描述
C ++ 11 std :: map< K,V>
类型具有 emplace
函数做许多其他容器。
std :: map< int,std :: string> m;
std :: string val {hello};
m.emplace(1,val);
此代码的工作原理是广告,放置 std :: pair& V>
,但是它导致发生键
和 val
的副本。
是否可以将值类型直接放入地图中?我们可以比调用 emplace
吗?
这里有一个更详细的例子:
struct Foo
{
Foo s){}
Foo(const Foo&)= delete;
Foo(Foo&&)= delete;
}
map< int,Foo> m;
m.emplace(1,2.3,string(hello)); // invalid
传递给 map :: emplace
转发到 map :: value_type
的构造函数,它是 pair< const Key ,Value>
。因此,您可以使用分段构造构造函数 std :: pair
以避免中间副本和移动。
std :: map< int,Foo& m;
m.emplace(std :: piecewise_construct,
std :: forward_as_tuple(1),
std :: forward_as_tuple(2.3,hello)); >现场演示
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")); // invalid
解决方案 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没有复制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!