![](/img/trans.png)
[英]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.