[英]getting error "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc"
[英]I keep getting this error "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc" when I run my code
这个错误出现在我的C++代码的“bfs”function。 我正在尝试编写图形数据结构的代码,但似乎有些东西未初始化或未按应有的方式存储输入。 谁能帮我解决这个问题?
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
void bfSearch(int n,vector<int> adj[])
{
cout<<"Inside function"<<endl;
vector<int> bfsv;
vector<int> vis(n+1,0);
for(int i=1;i<=n;i++)
{
if(!vis[i])
{
queue<int> q;
q.push(i);
vis[i]=1;
while(!q.empty())
{
int node=q.front();
q.pop();
bfsv.push_back(node);
for(auto it:adj[node])
{
q.push(it);
vis[it]=1;
}
}
}
}
for(auto it:bfsv)
{
cout<<it<<" ";
}
}
int main()
{
int n,m;
cin>>n>>m;
vector<int> adj[n+1];
for(int i=0;i<m;i++)
{
int u,v;
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
// vector<int> res=bfSearch(n,adj);
// for(auto it:res)
// {
// cout<<it<<" ";
// }
// cout<<endl;
bfSearch(n,adj);
}
是因为向量还是队列?
通常, std::bad_alloc
表示堆 memory 分配失败(并且您的系统内存不足)。
在您的情况下,这可能是由于控制台输入太高(对于n
、 m
、 u
或v
变量)引起的。
顺便说一句,总是首先尝试使用调试器来定位导致问题的确切代码行(以帮助人们尝试回答)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.