在抛出 'std::bad _alloc' 的实例后调用终止 what(): std::bad_alloc 在 c++ 中

Terminate called after throwing an instance of 'std::bad _alloc' what(): std::bad_alloc in c++

本文关键字:bad std alloc what c++ 终止 实例 调用      更新时间:2023-10-16
typedef struct abc{
    vector<int> path;
    int cost;
}nodetype;
vector<nodetype> population;
nodetype find_child(int rno)     
{
    vector<nodetype>::iterator it;
    nodetype retval;
    int total=0;
    for(it=population.begin(); it!= population.end() ; it++)
    {
        total= total+ (*it).cost;
        if(total>=rno)
        {
            retval = (*it);    
            break;
        }
    }
    return retval;
}
int main()
{
    vector<nodetype> :: iterator it;
    int total=0;
    for(it=population.begin();it!=population.end();it++)
    {
        total= total + (*it).cost;
    }
    //population vector is filled . So the total is not zero
   cin>>rno
    nodetype parent1= find_child(rno+1);     //1st call
    cin>>rno; 
    nodetype parent2= find_child(rno+1);    //2nd call
}

Population是上面定义的nodetype向量。在第一次调用中,程序没有崩溃。它成功地调用find_child()函数,将填充成本相加,直到它传递或等于作为参数传递的rno。但是在第二次调用中,它调用find_child()函数并进入函数中给出的if条件,但是当它执行"retval= (*it)"这一行时,它会崩溃,并在控制台打印给定语句"在抛出'std::bad_alloc' what(): std::bad_alloc"的实例后终止调用。帮我一下。

PS:-我一直在调试我的程序,一切都是正确的声明和初始化。当if条件中的语句被执行时,问题就出现了。这也是它在第一次调用时工作得很好,但当函数第二次调用时崩溃。

你在除以零。您的vector<nodetype> population;从未被填充,因此在此循环之后,total仍然是0:

for(it=population.begin();it!=population.end();it++)
{
    total= total + (*it).cost;
}

在这一行中,你用某个随机数除以那个零:

rno= rand() % total;