C ++ STL:在STL容器上哪种迭代方法更好? [英] C++ STL: Which method of iteration over a STL container is better?

查看:119
本文介绍了C ++ STL:在STL容器上哪种迭代方法更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能对某些人来说很轻松,但是对于STL容器,迭代的以下两种方法中哪一种更好? 为什么

This may seem frivolous to some of you, but which of the following 2 methods of iteration over a STL container is better? Why?

class Elem;
typedef vector<Elem> ElemVec;
ElemVec elemVec;

// Method 0
for (ElemVec::iterator i = elemVec.begin(); i != elemVec.end(); ++i)
{
    Elem& e = *i;
    // Do something
}

// Method 1
for (int i = 0; i < elemVec.size(); ++i)
{
    Elem& e = elemVec.at(i);
    // Do something
}

方法0似乎更清洁STL,方法1用较少的代码实现相同。容器上的简单迭代是在任何源代码中的所有地方出现的全部。所以,我倾向于选择方法1,这似乎减少视觉混乱和代码大小。

Method 0 seems like cleaner STL, but Method 1 achieves the same with lesser code. Simple iteration over a container is what appears all over the place in any source code. So, I'm inclined to pick Method 1 which seems to reduce visual clutter and code size.

PS:我知道迭代器可以做一个简单的索引。

PS: I know iterators can do much more than a simple index. But, please keep the reply/discussion focused on simple iteration over a container like shown above.

推荐答案

第一个版本适用于任何容器,因此在采用任何容器asa参数的模板函数中更有用。也可以想象更高效,即使对于向量。

The first version works with any container and so is more useful in template functions that take any container a s a parameter. It is also conceivably slightly more efficient, even for vectors.

第二个版本只适用于向量和其他整数索引的容器。它对于那些容器更为惯用,对于C ++的新手来说很容易理解,如果你需要用索引做别的事情,这是很有用的,这是不常见的。

The second version only works for vectors and other integer-indexed containers. It'd somewhat more idiomatic for those containers, will be easily understood by newcomers to C++, and is useful if you need to do something else with the index, which is not uncommon.

像往常一样,没有简单的这个更好的答案,恐怕。

As usual, there is no simple "this one is better" answer, I'm afraid.

这篇关于C ++ STL:在STL容器上哪种迭代方法更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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