【问题标题】:What's the point of iterators? [duplicate]迭代器的意义何在? [复制]
【发布时间】:2013-02-11 09:27:10
【问题描述】:

为什么要使用迭代器?

例如,如果我有这样的代码:

for (int i = 0; i < vec.size(); i++)
   cout << vec[i];

写作有什么好处

for (vector<int>::iterator it != vec.begin(); it != n.end(); ++it)
   cout << *it;

另外,为什么i &lt; vec.size()i++ 在第一个示例中更常见,而it != begin()++it 在第二个示例中更常见?增加它的方式有什么不同?为什么不总是使用等号?

我知道迭代器在 C++11 基于范围的 for 循环和一些 STD 算法中很有用,但是为什么我应该在普通代码中这样做,因为它更冗长?

【问题讨论】:

  • 如果 vec 是一个列表呢?
  • 都不如std::for_each(begin(vec), end(vec), [](int x) { std::cout &lt;&lt; x; });。避免一个错误和其他容易无意中犯的逻辑错误:使用算法和迭代器范围而不是手写循环。
  • @James McNellis 为什么更好?
  • 我从没见过有人写这个:vector&lt;int&gt;::iterator it != vec.begin();我很确定这是一个编译时错误。

标签: c++ c++11 iterator


【解决方案1】:

tl;dr 是迭代器在一般情况下对不同类型的对象工作得更好(例如 size() 方法可能很慢)。

如果您想了解更多信息:

Why use iterators instead of array indices?

Iterators.. why use them?

【讨论】:

    【解决方案2】:

    假设我们有这个代码:

    typedef std::vector<std::string> strings;
    
    strings strs;
    for( strings::const_iterator it = strs.begin(); it != strs.end(); ++it ) {
    }
    

    后来出于某种原因,我们决定切换到 std::list。所以我们只需要替换 typedef 和 code:

    typedef std::list<std::string> strings;
    
    strings strs;
    for( strings::const_iterator it = strs.begin(); it != strs.end(); ++it ) {
    }
    

    将像以前一样工作。但是带有索引变量的代码会失败。想象一下,如果您需要编写模板代码会怎样。

    【讨论】:

      【解决方案3】:

      重点是迭代器允许您迭代以通用方式支持迭代器的任何事物。

      至于它更冗长,额外的冗长并不可怕(您的示例可以使用auto 或使用基于范围的 C++11 for 循环稍微改进)但这确实是一个风格问题。

      【讨论】:

        【解决方案4】:

        并不是所有容器都具有随机访问权限,因此您可以对索引进行查找,因此标准化接口迭代器非常有用。考虑std::list。它不支持通过[] 运算符进行随机访问。

        考虑到这一点,为了跨多种异构类型的容器工作,许多 STL 函数(如 std::copy)采用迭代器。

        【讨论】:

          猜你喜欢
          • 2015-01-01
          • 2016-06-29
          • 1970-01-01
          • 2011-12-09
          • 1970-01-01
          • 2020-04-10
          • 2019-01-06
          • 2017-07-05
          • 2018-08-19
          相关资源
          最近更新 更多