[英]Made a recursive function in C++. Now asked to make a “tail-recursion” function
Here is a recursive function I came up with in order to fulfill the requirements of duplicating each letter in a string (ie "abc" to "aabbcc"): 这是我想出的递归函数,用于满足复制字符串中每个字母的要求(例如,“ abc”到“ aabbcc”):
#include <string>
#include <iostream>
using namespace std;
string repeater(string str){
if (str == ""){
return "";
}
else{
return str.substr(0,1) + str.substr(0,1) + repeater(str.substr(1));
}
}
int main(){
string test = "llama";
cout << "repeater(\"" << test << "\") returned: " << repeater(test) << endl;
}
Now I'm asked to make a "tail-recursive" function that does the same thing. 现在,我被要求做一个做同样事情的“尾递归”函数。 I'm reading up on it, and my text gives the following example of a "tail-recursive" function:
我正在阅读它,并且我的文字给出了“尾递归”函数的以下示例:
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n – 1);
}
This looks identical to the method I used to create my own. 这看起来与我用来创建自己的方法相同。 I need to hand in 2 versions of recursive functions.
我需要提交2个版本的递归函数。 Is mine already a "tail-recursive" function?
我的已经是“尾递归”功能了吗? If so, how would I make a forward recursive function (or, if the opposite is the case, vice-versa)?
如果是这样,我将如何制作正向递归函数(或者反之亦然)?
I suggest the following: 我建议以下内容:
string tail_repeater(string left, string right){
if (right == ""){
return left;
}
return tail_repeater(left + right.substr(0,1) + right.substr(0,1), right.substr(1));
}
string repeater(string str){
tail_repeater("", str);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.