首页 > 解决方案 > 在递归函数中,如何跳转到堆栈上的不同函数调用?

问题描述

为了让我的问题更清楚,我举个例子。假设我想实现一个递归函数,将 [1-10] 和 [15-20] 的数字范围相加,跳过 (10-15)。我想将 [15-20] 相加并跳过 (10-15) 堆栈上的函数调用,然后继续 [1-10]。我怎样才能做到这一点?

int summation(int x, int y) {
    if(x == y) return x;

    // Catch here and return sum of 15-20 back to calls of 1-10
    if(x == 10) 
        catch(int n) 
            return n;

    int sum = x + summation(x+1,y);

    // Skip function calls 10-15
    if(x==15) throw sum;

    return sum;

}

summation(1,20) // >> 160 or [1-10] = 55, [15,20] = 105 

我知道如何用不同的方法解决上面的例子,但是这个例子让我知道我正在尝试做什么。

标签: c++c++11c++14

解决方案


为了在正确的堆栈帧中设置 try/catch,您需要在更深入地递归之前知道跳过间隔的边缘。鉴于此,最好不要进行无用的函数调用,而不是使用异常来展开它们。例如:

int summation(int const x, int const y)
{
    if(x == y) return x;
    int const next = (x==10)? 15: (x+1);  // skip from 10 to 15 directly
    return x + summation(next, y);
}

避免异常还使您可以递归地编写函数:

int summation(int const x, int const y, int partial_sum = 0)
{
    partial_sum += x;
    if(x == y) return partial_sum;

    int const next = (x==10)? 15: (x+1);  // skip from 10 to 15 directly
    return summation(next, y, partial_sum);
}

推荐阅读