std::map emplace without copying value(std::map emplace 不复制值)
问题描述
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> 正在发生.
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
的参数会被转发给 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 不复制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::map emplace 不复制值


- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- GDB 不显示函数名 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 将 hdc 内容复制到位图 2022-09-04