【发布时间】:2021-01-14 02:12:15
【问题描述】:
我正在使用递归函数ans1 来寻找合适的字符串,
但我遇到运行时错误:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc**
void ans1(vector<int>a,int x , int val,string s,int req)
{
if(x<0||val>req)
return ;
if(val==req)
{
cout<<s<<endl;
return ;
}
char c='a'+x;
ans1(a,x-1,val,s,req);
s.push_back(c);
ans1(a,x,val+a[x],s,req);
}
有什么问题?
【问题讨论】:
-
你是怎么调用这个函数的?请发送minimal reproducible example。此外,如果您只是使用调试器单步调试程序,您应该能够自己找到问题。
-
你得到这个错误的输入值是什么?
-
您可以尝试使用
a和s的引用,以减少内存量
标签: c++ string algorithm recursion runtime-error