问题描述
我的同事宣称,对于对象类型,preincrement比post increment更有效
My workmate claims that for object types preincrement is more efficient than post increment
例如
std::vector<std::string> vec;
... insert a whole bunch of strings into vec ...
// iterate over and do stuff with vec. Is this more efficient than the next
// loop?
std::vector<std::string>::iterator it;
for (it = vec.begin(); it != vec.end(); ++it){
}
// iterate over and do stuff with vec. Is this less efficient than the previous loop?
std::vector<std::string>::iterator it;
for (it = vec.begin(); it != vec.end(); it++){
}
推荐答案
Postincrement必须返回迭代器在递增之前的值;所以,以前的值需要被复制到某个地方,然后改变它与适当的增量,所以它可以返回。额外的工作可能有点或很多,但它肯定不能小于零,相比预增量,它可以简单地执行增量,然后返回刚刚更改的值 - 无复制//保存//等等。
Postincrement must return the value the iterator had BEFORE it was incrementing; so, that previous value needs to be copied somewhere before altering it with the increment proper, so it's available to return. The extra work may be a little or a lot, but it certainly can't be less than zero, compared to a preincrement, which can simply perform the incrementing and then return the just-altered value -- no copying // saving // etc necessary.
所以,除非你特别必须有postincrement(因为你在某种程度上使用value before increment),你应该总是使用preincrement。
So, unless you specifically MUST have postincrement (because you're using the "value before increment" in some way), you should always use preincrement instead.
这篇关于++迭代器和迭代器++之间的性能差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!