【发布时间】:2021-08-15 04:56:36
【问题描述】:
我想将迭代模板函数 getSmallest 转换为递归函数,而不更改 main 中的任何内容(不更改函数参数等),因为在课堂上我们被教导要始终保持函数的公共接口相同(所以如果我们在一个大项目中工作,我们不会开始改变破坏整个程序的事情)
这是我要转换的程序:
// PRE: 0 <= start < end <= length of arr
// PARAM: arr = array of integers
// start = start index of sub-array
// end = end index of sub-array + 1
// POST: returns index of smallest value in arr{start:end}
template <class T>
int getSmallest(T arr[], int start, int end) {
int smallest = start;
for (int i = start + 1; i < end; ++i) {
if (arr[i] < arr[smallest]) {
smallest = i;
}
}
return smallest;
}
过去几个小时我一直在搜索课堂笔记、互联网和 stackoverflow 以寻求任何帮助,但这一切似乎与我的问题无关,所以我在这里问。
这是我想出的最好的尝试:
template <class T>
int getSmallest(T arr[], int start, int end)
{
int smallest = 0; //this should only run on the first recursion, not the rest
i = start;
if (i == end-1)
{
return smallest;
}
else
{
if (arr[i] < arr[smallest])
{
smallest = i;
}
return getSmallest<T>(arr, i, end);
}
}
我似乎无法让 int smallest = 0; 仅在第一次递归时运行,而当我的程序编译时,它在功能上毫无用处。
任何帮助将不胜感激。谢谢!
【问题讨论】:
-
你不能。递归函数将具有类似
int getSmallest(Iterator start, Iterator end, T currentmin)的签名。您可以实现此递归函数,并在内部调用具有旧签名的函数。 -
哦,这很有道理,难怪我感觉我一直在撞墙。谢谢!
-
@EOF 递归解决方案是possible,不改变函数签名。
-
@GuardedGauntlet447 递归
getSmallest()有问题。也许你想要if (i == end-0)? (它还有其他问题。) -
@chux-ReinstateMonica Ok:“具有相同行为的递归解决方案(O(1) 内存使用[需要消除尾调用,C 不保证],O(n) 运行时)没有签名更改是不可能的”。现在开心吗?