2

How can I solve the following situation, for any container-type which can use the for_each function -> for a vector this would be easy, because I could add a variable outside the call and give it as a reference parameter and increment it in the lambda function. So how can I get the current iterator in the lambda function?

std::for_each(container.begin(), container.end(), []() {
            //do-something and get the current iterator
});
mbed_dev
  • 1,450
  • 16
  • 33
  • 2
    I think this has already been answered here: http://stackoverflow.com/questions/3752019/how-to-get-the-index-of-a-value-in-a-vector-using-for-each – Joseph Evans Nov 17 '15 at 22:47

2 Answers2

3

Just do not call std::for_each() but use loop:

auto lambda = []( auto iter ) {}
for( auto it = container.begin(); it != container.end(); ++it ) lambda( it );

if you prefer you can write an algo around it:

template< class InputIt, class UnaryFunction >
UnaryFunction for_each_iter( InputIt first, InputIt last, UnaryFunction f )
{
    while( first != last ) f(first++);
    return f;
}
Slava
  • 43,454
  • 1
  • 47
  • 90
  • `UnaryFunction` cannot be `void` or it wouldn't be callable, thus you need a `return`. Also, even though iterators *should* be cheaply copyable, there's no reason to depend on it. – Deduplicator Nov 17 '15 at 23:09
2

You can write your own function:

template<class InputIt, class UnaryFunction>
UnaryFunction for_each_it(InputIt first, InputIt last, UnaryFunction f) {
    for (; first != last; ++first) (void) f(first);
    return f;
}
orlp
  • 112,504
  • 36
  • 218
  • 315