Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range-based for loop with boost::adaptor::indexed

The C++11 range-based for loop dereferences the iterator. Does that mean that it makes no sense to use it with boost::adaptors::indexed? Example:

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

I can always use a counter but I like indexed iterators.

  • Is it possible to use them somehow with range-based for loops?
  • What is the idiom for using range-based loops with an index? (just a plain counter?)
like image 963
gnzlbg Avatar asked May 17 '13 18:05

gnzlbg


1 Answers

This was fixed in Boost 1.56 (released August 2014); the element is indirected behind a value_type with index() and value() member functions.

Example: 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";
like image 141
ecatmur Avatar answered Sep 23 '22 03:09

ecatmur