以下面两行代码为例:

for (int i = 0; i < some_vector.size(); i++)
{
    //do stuff
}

这:

for (some_iterator = some_vector.begin(); some_iterator != some_vector.end();
    some_iterator++)
{
    //do stuff
}

有人告诉我第二种方法更可取。为什么会这样呢?


当前回答

我不使用迭代器的原因与我不喜欢foreach-statements的原因相同。当有多个内部循环时,如果不记住所有的局部值和迭代器名称,就很难跟踪全局/成员变量。我发现有用的是在不同的情况下使用两组指标:

for(int i=0;i<anims.size();i++)
  for(int j=0;j<bones.size();j++)
  {
     int animIndex = i;
     int boneIndex = j;


     // in relatively short code I use indices i and j
     ... animation_matrices[i][j] ...

     // in long and complicated code I use indices animIndex and boneIndex
     ... animation_matrices[animIndex][boneIndex] ...


  }

例如,我甚至不想将“animation_matrices[I]”缩写为一些随机的“anim_matrix”-name -iterator,因为这样你就不能清楚地看到这个值来自哪个数组。

其他回答

因为它更面向对象。如果你用一个索引迭代,你假设:

A)这些对象是有序的 B)这些对象可以通过索引获得 C)索引增量会影响每一项 D,指数从零开始

使用迭代器,你是在说“给我所有东西,这样我就可以使用它”,而不知道底层实现是什么。(在Java中,有些集合不能通过索引访问)

此外,使用迭代器,无需担心超出数组的边界。

已经有几个好观点了。我还有一些补充意见:

Assuming we are talking about the C++ standard library, "vector" implies a random access container that has the guarantees of C-array (random access, contiguos memory layout etc). If you had said 'some_container', many of the above answers would have been more accurate (container independence etc). To eliminate any dependencies on compiler optimization, you could move some_vector.size() out of the loop in the indexed code, like so: const size_t numElems = some_vector.size(); for (size_t i = 0; i Always pre-increment iterators and treat post-increments as exceptional cases.

for (some_iterator = some_vector.begin(); some_iterator != some_vector.end(); ++some_iterator){ //do stuff }

假设和可索引std::vector<>类似于容器,没有好的理由选择一个而不是另一个,按顺序遍历容器。如果必须频繁引用较旧或较新的元素索引,则使用索引版本更合适。

一般来说,使用迭代器是首选的,因为算法会使用它们,并且可以通过改变迭代器的类型来控制(并隐式记录)行为。数组位置可以用来代替迭代器,但是语法上的差异会很明显。

如果你喜欢接近金属/不相信它们的实现细节,就不要使用迭代器。 如果在开发过程中经常从一种集合类型切换到另一种集合类型,请使用迭代器。 如果您发现很难记住如何迭代不同类型的集合(可能您使用了来自几个不同外部源的几种类型),请使用迭代器来统一遍历元素的方法。这适用于切换一个链表和一个数组列表。

真的,就是这样。这并不是说您要获得更多的简洁,如果简洁确实是您的目标,您总是可以求助于宏。

索引需要一个额外的mul操作。例如,对于vector<int> v,编译器将v[i]转换为&v + sizeof(int) * i。

容器独立性