0

I have seen following snippet in Go. Getting index while doing range based for loop.

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

for i, v := range pow {
    fmt.Printf("2**%d = %d\n", i, v)
}

Is there any such provision in c++11 in range-based for loop? I know having a variable and incrementing is an option, but this is more powerful.

Dave C
  • 7,729
  • 4
  • 49
  • 65
Sudeep
  • 53
  • 1
  • 9
  • 3
    possible duplicate of [Find position of element in C++11 range-based for loop?](http://stackoverflow.com/questions/10962290/find-position-of-element-in-c11-range-based-for-loop) – awesoon Sep 06 '15 at 18:54
  • 1
    That, or http://stackoverflow.com/questions/6953128/need-iterator-when-using-ranged-based-for-loops – Brad Sep 06 '15 at 18:55
  • no, the question - is there an equivalent in Go to range-for from C++11 . –  Sep 06 '15 at 18:57
  • You could take a look at range-v3 at github, maybe there will be something interesting. – RippeR Sep 06 '15 at 22:18

1 Answers1

0

Boost has a very nice range adaptor indexed:

  #include <boost/range/adaptors.hpp>
  std::vector<std::string> list = {"boost", "adaptors", "are", "great"};
  for (auto v: list | boost::adaptors::indexed(1)) {
    printf("%ld: %s\n", v.index(), v.value().c_str());
  }

The output:

1: boost
2: adaptors
3: are
4: great

Here we index from 1 (boost::adaptors::indexed(1)), but we could easily index from 0 or any other value also.

Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93