在抛出 'std::bad _alloc' 的实例后调用终止 what(): std::bad_alloc 在 c++ 中
Terminate called after throwing an instance of 'std::bad _alloc' what(): std::bad_alloc in c++
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;
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- 获取错误:在抛出"std::bad::alloc"的实例后终止调用 what(): std::bad_alloc
- "std::vector"在调整大小时引发"bad allocation"异常
- 成员函数 bad() 的 std::ftsream 用于检查
- 正在使用std::string而不是char*bad
- 在抛出 'std::bad _alloc' 的实例后调用终止 what(): std::bad_alloc 在 c++ 中
- What is Scala for: getline(), std::cin.eof(), std::cin.bad()