C++ BFS使用不正确

C++ BFS使用不正确,c++,c++11,c++14,breadth-first-search,C++,C++11,C++14,Breadth First Search,嘿,我正在学习BFS,我想用它来知道从一个点到另一个点的距离,比如我的程序扫描 0 2 4 0 3 6 0 5 7 0 4 8 2 1 6 5 6 1 start, end, distance. 它应该告诉我从0到1到2到3的距离等等 所以在这个例子中,从0到1的距离是10,因为从0到2的距离是4,从2到1的距离是6 但我的程序在编译时说:在抛出'std::bad_alloc'实例后调用terminate 什么:性病::坏的 我希望你能帮我修好它,让它工作起来谢谢你 #include <

嘿,我正在学习BFS,我想用它来知道从一个点到另一个点的距离,比如我的程序扫描

0 2 4
0 3 6
0 5 7
0 4 8
2 1 6
5 6 1
start, end, distance.
它应该告诉我从0到1到2到3的距离等等

所以在这个例子中,从0到1的距离是10,因为从0到2的距离是4,从2到1的距离是6

但我的程序在编译时说:在抛出'std::bad_alloc'实例后调用terminate 什么:性病::坏的

我希望你能帮我修好它,让它工作起来谢谢你

 #include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
typedef vector<long long> vi;
typedef pair<long long,long long> pi;
typedef vector<pi> vpi;

#define FOR(i, a, b) for(ll i=ll(a); i<ll(b); i++)
#define ROF(i, a, b) for(ll i=ll(a); i>=ll(b); i--)
#define f first
#define s second
#define pb emplace_back
#define mp make_pair
#define SQ(a) (a)*(a)
#define all(a) (a).begin(), (a).end()

vector<pair<int,int> >adjacency_list[6];
bool visited[7];
int dist[7]={-1};
int main() {

dist[0]=0;
visited[0]=1;

for(int i=1;i<=6;i++){
  int a,b,c;
  cin>>a>>b>>c;
  adjacency_list[a].pb(mp(b,c));
    adjacency_list[b].pb(mp(a,c));
}

queue<int>q;

q.push(0);

while(!q.empty()){
  int current=q.front();
  q.pop();

for(auto i=adjacency_list[current].begin();i!=adjacency_list[current].end();i++){
if(!visited[i->first]){
  q.push(i->first);
  dist[i->first]=dist[current]+i->second;
  visited[i->first]= true;
  }
 }
}


for(int i=0;i<7;i++){
  cout<<i<<' '<<dist[i]<<endl;
}

 return 0;
}
邻接列表有6个元素,但邻接列表[b]中的b最多可以有6个元素,因此程序具有未定义的行为

我通过替换代码中所有不必要的typedef、defines和非标准include找到了这一点,用std::array替换原始数组,然后用at替换[],at将检测越界访问:

#include <vector>
#include <utility>
#include <iostream>
#include <queue>
#include <array>

std::array<std::vector<std::pair<int, int> >, 6> adjacency_list;
std::array<bool, 7> visited;
std::array<int, 7> dist = { -1 };
int main() {

    dist.at(0) = 0;
    visited.at(0) = 1;

    for (int i = 1; i <= 6; i++) {
        int a, b, c;
        std::cin >> a >> b >> c;
        adjacency_list.at(a).emplace_back(b, c);
        adjacency_list.at(b).emplace_back(a, c);
    }

    std::queue<int>q;

    q.push(0);

    while (!q.empty()) {
        int current = q.front();
        q.pop();

        for (auto i = adjacency_list.at(current).begin(); i != adjacency_list.at(current).end(); i++) {
            if (!visited.at(i->first)) {
                q.push(i->first);
                dist.at(i->first) = dist.at(current) + i->second;
                visited.at(i->first) = true;
            }
        }
    }

    for (int i = 0; i < 7; i++) {
        std::cout << i << ' ' << dist.at(i) << "\n";
    }

    return 0;
}

首先,不要使用include或namespace std。其次,当您初始化dist[]时,请记住,您只初始化第一个元素,而不是将它们全部初始化为-1。然后删除宏。对于int x=0,SQ宏将产生什么结果;SQx++;?请阅读以下帖子:嘿,但我不知道你是否可以提供一些代码来解决这个问题,因为我已经尝试了你的建议,但我无法让它工作。