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

2022-01-10 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.

相关文章