簡體   English   中英

遞歸函數中的運行時錯誤:在拋出“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM