C++ STL:STL 容器上的哪种迭代方法更好?

2022-01-07 00:00:00 containers iterator c++ 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 使用较少的代码实现了相同的效果.容器上的简单迭代是all出现在任何源代码中的地方.所以,我倾向于选择方法 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.

推荐答案

第一个版本适用于任何容器,因此在将任何容器作为参数的模板函数中更有用.可以想象,它的效率也略高一些,即使对于向量也是如此.

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.

相关文章