【问题标题】:Range-based for loop with boost::adaptor::indexed使用 boost::adaptor::indexed 的基于范围的 for 循环
【发布时间】:2013-05-13 00:50:22
【问题描述】:

C++11 基于范围的 for 循环取消引用迭代器。这是否意味着将它与boost::adaptors::indexed 一起使用没有意义?示例:

boost::counting_range numbers(10,20);
for(auto i : numbers | indexed(0)) {
  cout << "number = " i 
  /* << " | index = " << i.index() */ // i is an integer!
  << "\n";
}

我总是可以使用计数器,但我喜欢索引迭代器。

  • 是否可以通过基于范围的 for 循环以某种方式使用它们?
  • 将基于范围的循环与索引一起使用的习惯用法是什么? (只是一个普通的计数器?)

【问题讨论】:

  • indexed 很糟糕,因为它将 index() 方法添加到 iterator,而不是从取消引用迭代器返回的值。 ://
  • @Xeo 确实如此。我不时需要范围内元素的索引。首先我觉得很糟糕。然后,我介绍一个计数器。如果容器可以通过普通的旧循环轻松访问,我再次感到难过并将基于范围的循环重写为普通的旧循环。
  • 正如 Xeo 提到的 boost indexed 对此并不好。如果你不介意切换库,这里有一些基于 python 的 itertools 的 C++ 范围库,例如:github.com/ryanhaining/cppitertools
  • 注意:自 Boost 1.56(2014 年 8 月发布)以来,此问题已修复;该元素在value_type 后面间接使用index()value() 成员函数。
  • @gnzlbg,你能把boost::adaptor::indexed改成boost::adaptors::indexed吗,因为我花了一段时间才意识到s不见了?

标签: c++11 boost-range


【解决方案1】:

简短的回答(正如 cmets 中的每个人都提到的那样)是“对,这没有任何意义”。我也发现这很烦人。根据您的编程风格,您可能会喜欢我编写的“zipfor”包(只是一个标题):from github

它允许像

这样的语法
std::vector v;
zipfor(x,i eachin v, icounter) {
   // use x as deferenced element of x
   // and i as index
}

不幸的是,我无法找到使用基于范围的 for 语法的方法,不得不求助于“zipfor”宏:(

标题最初是为类似的东西设计的

std::vector v,w;
zipfor(x,y eachin v,w) {
   // x is element of v
   // y is element of w (both iterated in parallel)
}

std::map m;
mapfor(k,v eachin m)
   // k is key and v is value of pair in m

我对 g++4.8 的全面优化测试表明,生成的代码并不比手动编写慢。

【讨论】:

    【解决方案2】:

    此问题已在 Boost 1.56(2014 年 8 月发布)中得到修复;该元素在value_type 后面间接使用index()value() 成员函数。

    示例:http://coliru.stacked-crooked.com/a/e95bdff0a9d371ea

    auto numbers = boost::counting_range(10, 20);
    for (auto i : numbers | boost::adaptors::indexed())
        std::cout << "number = " << i.value()
            << " | index = " << i.index() << "\n";
    

    【讨论】:

      猜你喜欢
      • 2016-10-31
      • 1970-01-01
      • 2016-04-03
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 2013-01-04
      • 1970-01-01
      相关资源
      最近更新 更多