Search code examples
c++algorithmfor-looprangestandard-library

Is There a Standard Algorithm to Iterate Over a Range?


I need to call a lambda with every int in a range. Is there a standard algorithm that does this?

Ideally something equivalent:

for(auto i = 13; i < 42; ++i)[](int i){/*do something*/}(i);

Solution

  • As the other answers have mentioned if Boost is an option there is a better way to do this. If not, the best way is in the original question:

    for(auto i = 13; i < 42; ++i)[](int i){/*do something*/}(i);
    

    However, the future is bright, chris has mentioned proposal N4128 which is suggesting incorporating ranges into the standard alongside iterators.

    Now the draft is still in an early state, so there's a lot of clarification that is needed before how this will be used is nailed down. But one of the concepts is that all the STL algorithms would be overloaded to take views which is a thin wrapper providing access to the contained elements, but also an intelligent end position.

    Although a more complex example, chosen to showcase the power of view, the author's example in Motivation and Scope uses iota, which is exactly what we want:

    int total = accumulate(view::iota(1) |
                           view::transform([](int x){return x*x;}) |
                           view::take(10), 0);
    

    For our purposes we'd need to use generate_n in a for_each algorithm:

    for_each(view::generate_n(28,[]{static int i = 13; return i++;}),[](int i){/*do something*/});
    

    This would cause generate_n to be called 28 times (13 + 28 = 41), the created view would provide iteration over these numbers, feeding them into our original lambda in the for_each.

    chris has suggested that instead of generate_n a modification of iota might do the trick: iota(13, 41) It is key to note that whatever is used must have an end condition, because view lazily calls the generator, until no more items are requested. So this for_each(view::iota(10), [](int i){/*do something*/}); defines an infinite loop.