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 不复制值
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
