Ale*_*lex 3 c++ stack-overflow recursion
我是第一个C++类的编程学生,最近我们获得了一个赋值来实现一个递归程序,该程序查找给定字符串中给定子字符串的第一次出现.
例如:
int StringIndex("Mississippi", "sip"); // this would return 6
Run Code Online (Sandbox Code Playgroud)
我们给出的提示是使用递归辅助函数,该函数将索引作为参数.
这是我到目前为止所做的:
int index_of(string s, string t)
{
int index = 0;
if (s[index] == NULL)
return -1;
else if (starts_with(s, t, ++index))
{
return index;
}
return index_of(s, t);
}
bool starts_with(string s, string t, int index)
{
if (t[index] != s[index] || s[index] == NULL)
return false;
return starts_with(s, t, ++index);
}
Run Code Online (Sandbox Code Playgroud)
我收到堆栈溢出错误,我不明白为什么.那么有人会介意帮助我理解为什么我会收到这个错误吗?并帮助我指出正确的方向,如何解决它?
int index_of(string s, string t)
{
...
// Your are calling yourself without modifying the
// input parameters. If you get here once, you'll
// never break out.
return index_of(s, t);
}
Run Code Online (Sandbox Code Playgroud)
什么都没有改变s,t所以这永远不会停止.
| 归档时间: |
|
| 查看次数: |
1754 次 |
| 最近记录: |