重载std :: unordered_map :: insert [英] overload of std::unordered_map::insert

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

问题描述

您会教我为什么

  std :: unordered_map :: insert(const value_type&)

  ;类P> std :: unordered_map :: insert(P&&)

>

我认为 insert(P&& amp;)可以作为 insert(const value_type&

解决方案

这两个重载

  auto std :: unordered_map :: insert(const value_type&) - > ... 

template< class P>
auto std :: unordered_map :: insert(P&&) - > ...

有它们的优点,也不能完全取代另一个。第一个似乎是第二个的特殊情况,因为 P 可能被推导为 const value_type& code>。关于第二个重载的好处是,你可以避免不必要的副本。例如,在这种情况下:

  mymap.insert(make_pair(7,seven)); 

这里,make_pair的结果实际上是一个 pair< int,const char *> ,而 value_type 可能是 pair< const int,string> 。所以,不是创建一个临时的 value_type 对象并将其复制到容器中,我们可以直接创建



另一方面,这将是很好的,如果这个工作以及:

  mymap.insert({7,seven}); 

但这个列表实际上不是一个表达式!由于这个原因,编译器不能推导出第二个重载的P。第一个重载是可行的,因为你可以复制初始化 pair< const int,string> 这样的列表。


Would you teach me why both

std::unordered_map::insert(const value_type&)

and

template<class P> std::unordered_map::insert(P&&)

exist in the standard?

I think that insert(P&&) can serve as insert(const value_type&).

解决方案

Both of these overloads

auto std::unordered_map::insert(const value_type&) -> ...

template<class P>
auto std::unordered_map::insert(P&&) -> ...

have their advantages and neither can fully replace the other. The first one seems like a special case of the second one since P might be deduced to be const value_type&. The nice thing about the 2nd overload is that you can avoid unnecessary copies. For example, in this case:

mymap.insert(make_pair(7,"seven"));

Here, the result of make_pair is actually a pair<int, const char*> whereas value_type might be pair<const int, string>. So, instead of creating a temporary value_type object and copying it into the container, we have the chance of directly creating the value_type object into the map by converting the argument and/or moving its members.

On the other hand, it would be nice if this worked as well:

mymap.insert({7,"seven"});

But this list is actually not an expression! The compiler can't deduce P for the second overload because of that. The first overload is still viable since you can copy-initialize a pair<const int,string> parameter with such a list.

这篇关于重载std :: unordered_map :: insert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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