std :: map emplace没有复制值 [英] std::map emplace without copying value

查看:1279
本文介绍了std :: map emplace没有复制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"));

Live demo

这篇关于std :: map emplace没有复制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆