C++使用for循环的最佳方式 [英] c++ best way to use for loop
本文介绍了C++使用for循环的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题浮现在我的脑海里... 我有一个std::向量来迭代: 迭代的最佳方式(更快)是什么?
以下是使用迭代器的代码:
// using the iterator
for( std::vector <myClass*>::iterator it = myObject.begin( ); it != myObject.end( ); it++ )
{
(*it)->someFunction( );
}
这里是‘正常’模式...
// normal loop
for( int i = 0; i < myObject.Size( ); i++ )
{
myObject[i]->someFunction( );
}
谢谢您的建议!
推荐答案
两者都不会真正快,因为在大多数实现中,vector<T>::iterator
只是T*
的类型定义,size
是缓存的。
但做++it
而不是it++
是一个好习惯。后者涉及创建临时。
for(std::vector <myClass*>::iterator it = myObject.begin( );
it != myObject.end( );
++it)
^^^^
在具有非平凡迭代器的map
、list
等其他容器上,后增量和前增量之间的差异可能会变得很明显。
这篇关于C++使用for循环的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文