【问题标题】:Runtime Error in a recursive function : terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc递归函数中的运行时错误:在抛出“std::bad_alloc”what() 的实例后调用终止:std::bad_alloc
【发布时间】: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。此外,如果您只是使用调试器单步调试程序,您应该能够自己找到问题。
  • 你得到这个错误的输入值是什么?
  • 您可以尝试使用as 的引用,以减少内存量

标签: c++ string algorithm recursion runtime-error


【解决方案1】:

您正在通过值传递a! 这意味着您正在为每个递归步骤创建std::vector&lt;int&gt; 的副本。如果a 很大,则您分配了大量内存。将参数更改为const vector&lt;int&gt;&amp; a,问题应该得到解决。

如果是s,问题会更复杂,因为您正在修改它。您可以使用string &amp;s,但您必须记住在从递归返回时恢复旧值,以避免副作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多