递增迭代器:++it 比 it++ 更有效吗?

编程入门 行业动态 更新时间:2024-10-19 21:42:28
本文介绍了递增迭代器:++it 比 it++ 更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Possible Duplicate: Is there a performance difference between i++ and ++i in C++?

I am writing a program where an iterator is used to loop through a std::vector. Somebody told me that doing ++it in the for statement leads to more efficient code. In other words, they are saying that:

for ( vector<string>::iterator it=my_vector.begin(); it != my_vector.end(); ++it )

runs faster than

for ( vector<string>::iterator it=my_vector.begin(); it != my_vector.end(); it++ )

Is this true? If it is, what is the reason behind the efficiency improvement? All it++/++it does is move the iterator to the next item in the vector, isn't it?

解决方案

The reason behind the preincrement being faster is that post-increment has to make a copy of the old value to return. As GotW #2 put it, "Preincrement is more efficient than postincrement, because for postincrement the object must increment itself and then return a temporary containing its old value. Note that this is true even for builtins like int."

GotW #55 provides the canonical form of postincrement, which shows that it has to do preincrement plus some more work:

T T::operator++(int) { T old( *this ); // remember our original value ++*this; // always implement postincrement // in terms of preincrement return old; // return our original value }

As others have noted, it's possible for some compiler to optimize this away in some cases, but if you're not using the return value it's a good idea not to rely on this optimization. Also, the performance difference is likely to be very small for types which have trivial copy constructors, though I think using preincrement is a good habit in C++.

更多推荐

递增迭代器:++it 比 it++ 更有效吗?

本文发布于:2023-11-25 22:53:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631669.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:更有效   迭代

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!