...

/

Fibers in Range Implementations

Fibers in Range Implementations

You will learn how fibers are used with range implementations in this lesson.

We'll cover the following...

Almost every range needs to store some information to remember its state of iteration. This is necessary for it to know what to do when its popFront() is called next time. Most range examples that we covered earlier store some kind of state to achieve their tasks.

FibonacciSeries example

For example, FibonacciSeries that we have defined earlier was keeping two member variables to calculate the next next number in the series:

Press + to interact
struct FibonacciSeries {
int current = 0;
int next = 1;
enum empty = false;
int front() const {
return current;
}
void popFront() {
const nextNext = current + next;
current = next;
next = nextNext;
}
}

While maintaining the iteration state is trivial for some ranges like FibonacciSeries, it is surprisingly harder for some others, e.g., recursive data structures like binary search trees. This is surprising because ,for such data structures, the same algorithms are trivial when implemented recursively.

For example, the following recursive implementations of insert() and ...