3

when working with a for loop such as this

for(int i=0 ; i<collection.size() ; i++)
{
  //current index is i and total size is size
}

However I have something like this

  for_each(collection.begin(), collection.end(), [&](MyTuple& e)
        {
            //Total size would be collection.size()
            //How would i get the current index ?
        });
Rajeshwar
  • 11,179
  • 26
  • 86
  • 158
  • 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), not 100% the same but the principle perhaps is. – user657267 Aug 05 '14 at 09:30

2 Answers2

2

You have to put a counter variable above the loop, capture it in the lambda and increment it each time. As this is quite awkward, I suggest you don't use for_each when the index of the element is important (just my opinion).

size_t count = 0;
for_each(collection.begin(), collection.end(), [&count](MyTuple& e)
{
    ...
    ++count;
});
Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
1

Using the std::for_each algorithm on an iterator range won't give you the index without applying a special adapter to the iterators. However, using a vanilla for on an iterator range can give you the index like this:

for(auto it = collection.begin(); it != collection.end(); ++it)
{
    const auto index = std::distance(collection.begin(), it);
    ...
}

Note that index above is only meaningful with "index into an array"-semantics for random access iterators.

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122
  • I would prefer to use `operator -` on the iterators, so that if they are not random-access, it won't compile, as distance could be slow. – Neil Kirk Aug 05 '14 at 10:05