c++ - 在递归函数中,如何跳转到堆栈上的不同函数调用?
问题描述
为了让我的问题更清楚,我举个例子。假设我想实现一个递归函数,将 [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
我知道如何用不同的方法解决上面的例子,但是这个例子让我知道我正在尝试做什么。
解决方案
为了在正确的堆栈帧中设置 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);
}
推荐阅读
- javascript - 为什么我的自定义操作按钮不起作用
- python - 我如何比较两个列表中的参数
- azure - Azure AD 扩展属性 + MS Graph API PATCH = 权限不足,无法完成操作
- css - 如何移动包含图像的 div
- python-3.x - 如何使用python和pandas将空值列替换为列表中存储的值以及CSV中的相应索引?
- namespaces - 如何让 RequireJS 为 TYPO3 BE 正确解析命名空间?
- java - 500 内部服务器错误,获取请求时出现 NullPointerException
- c# - Xamarin 表单选择器确定或取消按钮按下检测
- delphi - 如何通过 Delphi Winapi.Mapi 修复“发送电子邮件”?
- ios - UICollectionView 单元格布局未重置先前设置的边框