Home > Back-end >  C use function's output as functions input n times
C use function's output as functions input n times

Time:11-21

I'm sorry for the weird title. I don't know how to word this. If I have function func() How do I do this:

func(func(func(func(func(x)))))

where it repeats N times?

I'm trying to implement Conway's Game of Life. I have a function that takes a vector and outputs another vector, which is the next generation of the input vector. So generation 3's vector would be func(func(func(x))).

CodePudding user response:

The easy way, simply using for loop:

int x = some_initial_value;
for (int i = 0; i < NUMBER_OF_ITERATIONS;   i)
{
    x = func(x);
}

CodePudding user response:

While the 'easy way' works in most cases, I'd like to provide you a way to do in in cases where return type (for a given argument type) might differ from argument type:

template<size_t i, typename F, typename Arg>
auto times(F f, const Arg& arg) {
    if constexpr (i == 0) {
        return arg;
    } else {
        return times<i - 1>(f, f(arg));
    }
}

// usage: times<5>(func, x);
  • Related