为什么使用迭代器而不是数组索引? [英] Why use iterators instead of array indices?

查看:95
本文介绍了为什么使用迭代器而不是数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采取以下两行代码:

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
}



'告诉第二种方式是首选。为什么是这样?

I'm told that the second way is preferred. Why exactly is this?

推荐答案

第一种形式只有在vector.size这对于向量是正确的,但不是列表,例如。另外,你打算在循环体内做什么?如果你计划访问

The first form is efficient only if vector.size() is a fast operation. This is true for vectors, but not for lists, for example. Also, what are you planning to do within the body of the loop? If you plan on accessing the elements as in

T elem = some_vector[i];

那么你假设容器有 operator [] std :: size_t)定义。同样,对于向量,这是真的,但不是其他容器。

then you're making the assumption that the container has operator[](std::size_t) defined. Again, this is true for vector but not for other containers.

迭代器的使用使你更接近容器的独立性。您不是对随机访问能力或快速 size()操作做出假设,只是容器具有迭代器功能。

The use of iterators bring you closer to container independence. You're not making assumptions about random-access ability or fast size() operation, only that the container has iterator capabilities.

您可以使用标准算法进一步增强代码。根据你想要实现什么,你可以选择使用 std :: for_each() std :: transform()等。通过使用标准算法而不是显式循环,你可以避免重新创造轮子。您的代码可能会更有效(给定正确的算法),正确且可重复使用。

You could enhance your code further by using standard algorithms. Depending on what it is you're trying to achieve, you may elect to use std::for_each(), std::transform() and so on. By using a standard algorithm rather than an explicit loop you're avoiding re-inventing the wheel. Your code is likely to be more efficient (given the right algorithm is chosen), correct and reusable.

这篇关于为什么使用迭代器而不是数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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