以下面两行代码为例:

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
}

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


当前回答

迭代器的另一个好处是,它们更好地允许你表达(和执行)你的const-preference。这个例子确保你不会在循环中改变向量:


for(std::vector<Foo>::const_iterator pos=foos.begin(); pos != foos.end(); ++pos)
{
    // Foo & foo = *pos; // this won't compile
    const Foo & foo = *pos; // this will compile
}

其他回答

这两个实现都是正确的,但我更喜欢'for'循环。由于我们已经决定使用Vector容器而不是其他容器,因此使用索引将是最好的选择。对vector使用迭代器将失去将对象放在连续内存块中的好处,这有助于简化对它们的访问。

还没有人提到索引的一个优点是,当您向std::vector这样的连续容器添加索引时,它们不会失效,因此您可以在迭代期间向容器添加项。

这也可以用迭代器实现,但必须调用reserve(),因此需要知道要追加多少项。

第二种形式更准确地表示您正在做什么。在你的例子中,你并不关心i的值,你所需要的只是迭代器中的下一个元素。

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

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<>类似于容器,没有好的理由选择一个而不是另一个,按顺序遍历容器。如果必须频繁引用较旧或较新的元素索引,则使用索引版本更合适。

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

如果要在迭代vector时向其添加/删除项,则可能需要使用迭代器。

some_iterator = some_vector.begin(); 
while (some_iterator != some_vector.end())
{
    if (/* some condition */)
    {
        some_iterator = some_vector.erase(some_iterator);
        // some_iterator now positioned at the element after the deleted element
    }
    else
    {
        if (/* some other condition */)
        {
            some_iterator = some_vector.insert(some_iterator, some_new_value);
            // some_iterator now positioned at new element
        }
        ++some_iterator;
    }
}

如果使用索引,则必须在数组中上下移动项以处理插入和删除。