使用迭代器和索引访问向量元素有什么区别? [英] What is the difference between accessing vector elements using an iterator vs an index?

查看:524
本文介绍了使用迭代器和索引访问向量元素有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用迭代器与索引访问向量元素有什么好处?

What advantages are there in accessing vector elements using an iterator vs an index?

推荐答案

为什么迭代器比索引更好?

Why are iterators better than indexes?


  • 在索引不可用的情况下(例如std :: list,
    示例)。

  • 在调用接受迭代器
    的泛型函数的情况下。

  • 编写应该与
    一起使用的函数模板时多个容器类型。

  • 它们的存在是为了在所有容器中创建 uniform 并且能够使用
    所有容器的迭代器以及常规指针所有标准的
    算法。

  • 迭代器可以指向除了概念之外不存在的序列。
    例如,你可以创建一个迭代器类来逐步执行素数
    数字而不必实际构建素数容器。

  • In the cases where index is not available (like with std::list, for example).
  • In the case where a generic function accepting an iterator is called.
  • When writing a function template that is supposed to work with more than one container type.
  • They exist to create uniformity among all containers and ability to use all containers' iterators as well as regular pointers in all standard algorithms.
  • Iterators can point to sequences that don't exist except as a concept. For instance, you can make an iterator class that steps through prime numbers without actually having to build a container of primes.

但是,如果忽略不支持随机访问的容器类型(列表,集等),迭代器仍会提供

However, if ignoring container types that do not support random access (list, set, etc.), iterators still offer


  • 像语义一样的指针(想想string :: iterator与char *)。

  • 广义概念可以在
    容器内的元素之外迭代使用。

  • 在少数情况下,性能优于容器成员函数。

这篇关于使用迭代器和索引访问向量元素有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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