문제

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?)
도움이 되었습니까?

해결책

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";

다른 팁

The short answer (as everyone in the comments mentioned) is "right, it makes no sense." I have also found this annoying. Depending your programming style, you might like the "zipfor" package I wrote (just a header): from github

It allows syntax like

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

Unfortunately, I cannot figure a way to use the ranged-based for syntax and have to resort to the "zipfor" macro :(

The header was originally designed for things like

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

and

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

My tests on g++4.8 with full optimizations shows that the resulting code is no slower than writing it by hand.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top