I'm using Visual Studio 2012 so C++11 is mostly OK... boost is also fine, but I would prefer to avoid other libreries, at least not widley used ones.
I want to create a forward only iterator that returns an infinite sequence, in the most elegant way possible. For example a sequence of all the natural numbers.
Basically I want the C++ equivilent of this f# code:
let nums =
    seq { while true do
            yield 1
            yield 2
        }
the above code basically creates an enumerator that returns [1;2;1;2...]
I know I could do this by writing a class, but there's got to be a shorter way with all the new lambdas and all...
Is this what you want:
#include <iostream>
#include <vector>
int main() 
{
    auto nums = []
    {
        static unsigned x = 2;
        return ( x++ % 2 ) + 1;
    };
    std::vector< int > v{ nums(), nums(), nums(), nums(), nums() };
    for( auto i : v )
    {
        std::cout << i;
    }
    return 0;
}
or I have misunderstood the question?
The simpler thing, if you can depend on boost is to write something like this:
int i = 0;
auto gen = boost::make_generator_iterator([=]() { return i++; });
C++14 version:
auto gen = boost::make_generator_iterator([i=0]() { return i++;});
Documentation is here.
P.S.: I'm not sure if it will work without result_type member, which C++03 functor would need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With