STL映射插入效率:[]与插入 [英] STL map insertion efficiency: [] vs. insert

查看:156
本文介绍了STL映射插入效率:[]与插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种地图插入方式:

m[key] = val;

m.insert(make_pair(key, val));

我的问题是,哪个操作更快?
人们通常说第一个更慢,因为STL标准首先'插入'默认元素,如果'key'不存在于map中,然后将'val'赋给默认元素。

My question is, which operation is faster? People usually say the first one is slower, because the STL Standard at first 'insert' a default element if 'key' is not existing in map and then assign 'val' to the default element.

但我没有看到第二种方法是更好的,因为'make_pair'。 make_pair实际上是与< code>对< T1,T2>(key,val)相比,'pair'无论如何,它们都做了两个赋值,一个是将key赋值给pair.first,另一个是将val赋值给pair.second。在配对后,map插入由'pair.second'初始化的元素。

But I don't see the second way is better because of 'make_pair'. make_pair actually is a convenient way to make 'pair' compared to pair<T1, T2>(key, val). Anyway, both of them do two assignments, one is assigning 'key' to 'pair.first' and two is assigning 'val' to 'pair.second'. After pair is made, map inserts the element initialized by 'pair.second'.

所以第一种方法是1.' (val)'2.赋值
第二种方式是赋值2.' typeof(val)的复制构造'

So the first way is 1. 'default construct of typeof(val)' 2. assignment the second way is 1. assignment 2. 'copy construct of typeof(val)'

推荐答案

两者都完成不同的事情。

Both accomplish different things.

m[key] = val;

如果不存在,或者如果它已经存在,它将覆盖映射到的旧值。

Will insert a new key-value pair if the key doesn't exist already, or it will overwrite the old value mapped to the key if it already exists.

m.insert(make_pair(key, val));

只有插入还存在,它将永远不会覆盖旧的值。所以,相应地选择你想要完成什么。

对于问题什么是更有效:profile。 :P大概是我说的第一种方式。分配(aka copy)是两种方式的情况,所以唯一的区别在于构造。我们都知道和应该实现,默认的结构应该基本上是一个无操作,因此是非常有效的。副本是一个副本。所以在方式一,我们得到一个无操作和一个副本,在方式二,我们得到两个副本。

编辑:最后,相信你的剖析您。我的分析是像@Matthieu在他的评论中提到的,但这是我的猜测。 :)

Will only insert the pair if key doesn't exist yet, it will never overwrite the old value. So, choose accordingly to what you want to accomplish.
For the question what is more efficient: profile. :P Probably the first way I'd say though. The assignment (aka copy) is the case for both ways, so the only difference lies in construction. As we all know and should implement, a default construction should basically be a no-op, and thus be very efficient. A copy is exactly that - a copy. So in way one we get a "no-op" and a copy, and in way two we get two copies.
Edit: In the end, trust what your profiling tells you. My analysis was off like @Matthieu mentions in his comment, but that was my guessing. :)

然后,我们有C ++ 0x到来,第二种方式的双拷贝,因为这对可以简单地移动。所以,最后,我认为它落回到我的第一点:使用正确的方式来完成你想做的事情。

Then, we have C++0x coming, and the double-copy on the second way will be naught, as the pair can simply be moved now. So in the end, I think it falls back on my first point: Use the right way to accomplish the thing you want to do.

这篇关于STL映射插入效率:[]与插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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