递归函数中的运行时错误:在抛出 what() 的实例后调用'std::bad_alloc'终止::bad_alloc
Runtime Error in a recursive function : terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
我正在使用递归函数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);
}
问题出在哪里?
您正在按值传递a
!这意味着您正在为每个递归步骤创建std::vector<int>
的副本。如果a
很大,则会分配大量内存。将参数更改为const vector<int>& a
,问题应该得到解决。
在s
的情况下,由于您正在修改它,所以问题更复杂。您可以使用string &s
,但在递归返回时必须记住恢复旧值,以避免副作用。
相关文章:
- 使用来自 Excel VBA 的 C++ dll 时"Bad DLL calling convention" - 如何解决?
- C++17 编解码器在将标准::字符串转换为标准::字符串时抛出"bad conversion"
- 对于代理容器上的迭代器来说,"least bad implementation"可能是什么?
- 组件对象模型 (COM):IMalloc::Alloc 在哪里分配内存?
- 获取错误:在抛出"std::bad::alloc"的实例后终止调用 what(): std::bad_alloc
- 为什么 GetSystemMetrics (SM_CXVIRTUALSCREEN) 返回'bad'值?
- 将 lambda 传递给 STL 集时出错"bad function call"
- 新的 C++14 位分隔符处"Bad Character" Eclipse Oxygen 错误
- 使用 #define 被认为是"bad practice"吗?
- "400 Bad request"使用 OpenSSL BIO 进行请求时
- CGAL:Hausdorff距离不良Alloc
- 解密文件AES_256_CBC返回"bad decrypt"错误
- 在C++流中,eof(),fail(),bad()和good()有什么区别
- C STD ::初始化类对象中的Alloc错误错误
- make / gcc:"bad build"的可能原因是什么?
- 什么是地址0xbaddc0dedeadbead "Bad decode dead bead"
- 在多线程环境中,什么可能导致"bad file descriptor"?
- 尝试解决HackerBank上的BFS挑战时出现错误的alloc异常
- "std::vector"在调整大小时引发"bad allocation"异常
- 尝试使用 execp、dup2 和管道实现 shell,挂起或"bad file descriptor"