Create a generator as iterators
A generator is an iterator that generates its own sequence of values. It does not use a container. It creates values on the fly, returning one at a time as needed. A C++ generator stands on its own; it does not need to wrap around another object.
In this recipe, we'll build a generator for a Fibonacci sequence. This is a sequence where each number is the sum of the previous two numbers in the sequence, starting with 0 and 1:
The first ten values of the Fibonacci sequence, not counting zero, are: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. This is a close approximation of the golden ratio found in nature.
How to do it…
A Fibonacci sequence is often created with a recursive loop. Recursion in a generator can be difficult and resource-intensive, so instead we'll just save the previous two values in the sequence and add them together. This is more efficient.
...