迭代通过容器的最佳方式 [英] Best way to iterate through a container
本文介绍了迭代通过容器的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这两种方式迭代容器/您喜欢哪一种方式和原因的优点/缺点是什么?
for(MyClass :: iterator i = m.begin(),e = m.end(); i!= e; i ++)
{
// ...
} b $ b
或
$ c> for(MyClass :: iterator i = m.begin(); i!= m.end(); i ++)
{
// ...
}
子问题:i ++ or ++ i?为什么?
解决方案
如果迭代器不重要(即不是指针),++ i肯定会更快
第一种形式有点快,但是如果你删除或插入可能是错误的
对于容器上的简单迭代,我使用
#define foreach BOOST_FOREACH // in some header
foreach(MyType& element,any_container){
//处理元素
}
大部分时间是为了简洁和清晰。
What are the Advantages/Drawbacks of these two ways of iterating through a container / which one do you prefer and why:
for (MyClass::iterator i = m.begin(), e = m.end() ; i != e ; i++) { // ... }
or
for (MyClass::iterator i = m.begin() ; i != m.end() ; i++) { // ... }
Subsidiary question: i++ or ++i? Why?
解决方案If the iterator is non-trivial (ie. not a pointer), ++i is definitely faster as it doesn't involves a copy to a temporary, which may or may not be optimized out.
The first form is a little faster but could be wrong if you erase or insert things in the loop.
For simple iteration over a container I use
#define foreach BOOST_FOREACH // in some header foreach(MyType &element, any_container) { // deal with element }
most of the time for succinctness and clarity.
这篇关于迭代通过容器的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文