You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中将函数输出作为输入重复调用N次?

实现函数连续调用N次的几种方法

针对你提到的康威生命游戏场景(函数接收vector并返回下一代状态的vector),以下是几种实现连续调用N次func的方案:

1. 循环迭代(最直观易读)

用变量保存当前状态,通过循环重复调用func更新状态,适合任意N值,无递归深度限制:

vector<...> apply_func_n_times(vector<...> initial_state, int n) {
    vector<...> current = initial_state;
    for (int i = 0; i < n; ++i) {
        current = func(current);
    }
    return current;
}

比如要得到第3代,传入初始状态和n=3即可。

2. 递归实现

如果N不大,可通过递归逐层调用,直到N为0时返回当前状态:

vector<...> apply_func_n_times(vector<...> state, int n) {
    if (n == 0) {
        return state;
    }
    return apply_func_n_times(func(state), n - 1);
}

注意:N过大时递归可能引发栈溢出,优先选循环方案。

3. 利用标准库工具(C++23及以上)

C++23新增的std::invoke_n可直接指定调用次数,结合函数对象实现:

#include <functional>

vector<...> apply_func_n_times(vector<...> initial_state, int n) {
    return std::invoke_n(std::bind_front(func, std::placeholders::_1), n, initial_state);
}

也可用std::accumulate模拟调用次数:

#include <numeric>
#include <vector>

vector<...> apply_func_n_times(vector<...> initial_state, int n) {
    return std::accumulate(std::begin(std::vector<int>(n)), std::end(std::vector<int>(n)), 
                           initial_state, [](auto state, auto) {
                               return func(state);
                           });
}

内容的提问来源于stack exchange,提问作者apchrkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:50:47