![](/img/trans.png)
[英]getting error "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc"
[英]Runtime Error in a recursive function : terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
我正在使用遞歸函數ans1
來查找合適的 string ,但出現運行時錯誤:
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
,但您必須記住在從遞歸返回時恢復舊值,以避免副作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.