Getting the current index from a for_each loop
when working with a for loop like
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 ?
});
source to share
You have to place a control variable above the loop, capture it in a lambda and increment it every time. Since this is rather inconvenient, I suggest you not use for_each
when the item index is important (just my opinion).
size_t count = 0;
for_each(collection.begin(), collection.end(), [&count](MyTuple& e)
{
...
++count;
});
source to share
Using an algorithm std::for_each
on a range of iterators will not give you an index without applying a special adapter to the iterators. However, using vanilla for
on a range of iterators can give you an index like this:
for(auto it = collection.begin(); it != collection.end(); ++it)
{
const auto index = std::distance(collection.begin(), it);
...
}
Note that the index
above only makes sense with "index to array" semantics for random access iterators.
source to share