Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an infinite sequence in C++

Tags:

c++

c++11

boost

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...

like image 801
AK_ Avatar asked Nov 28 '13 11:11

AK_


2 Answers

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?

like image 124
Kiril Kirov Avatar answered Oct 17 '22 02:10

Kiril Kirov


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.

like image 3
Germán Diago Avatar answered Oct 17 '22 01:10

Germán Diago