Range for loop with boost :: adapter :: indexed

The C ++ 11 loop-based environment shares an iterator. Does this mean that it makes no sense to use it with boost::adaptor::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 a range for loops?
  • What is the idiom for using range based index loops? (just a simple counter?)
+6
source share
2 answers

This was fixed in Boost 1.56 (released in August 2014); The element is indirect for value_type with the functions index() and value() .

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"; 
+2
source

The short answer (as everyone in the comments say) is "right, that’s pointless." I also found this annoying. Depending on your programming style, you might like the "zipfor" package I wrote (just the title): from github

It allows you to use the syntax as

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

Unfortunately, I cannot figure out how to use range-based syntax and resort to the zipfor macro :(

The headline was originally intended 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 g ++ 4.8 tests with full optimization show that the resulting code is no slower than writing it manually.

0
source

Source: https://habr.com/ru/post/945290/


All Articles