为什么使用迭代器而不是数组索引?

编程入门 行业动态 更新时间:2024-10-22 15:37:02
本文介绍了为什么使用迭代器而不是数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

采取以下两行代码:

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.

更多推荐

为什么使用迭代器而不是数组索引?

本文发布于:2023-11-29 16:44:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646981.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   而不是   索引   迭代

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!