C++ 我的C+中出现了分段错误+;使用std::cin时的代码 我正在解决一个算法问题(这是一个拓扑排序问题,是韩语),在测试例子输入时,在输入中间得到分段错误。 7 9 1 2 4 1 3 2 1 4 3 2 6 3 2 7 5 3 5 1 4 6 4 5 6 2 // here when I input 6, I get segmentation fault 6 7 5 1 7

C++ 我的C+中出现了分段错误+;使用std::cin时的代码 我正在解决一个算法问题(这是一个拓扑排序问题,是韩语),在测试例子输入时,在输入中间得到分段错误。 7 9 1 2 4 1 3 2 1 4 3 2 6 3 2 7 5 3 5 1 4 6 4 5 6 2 // here when I input 6, I get segmentation fault 6 7 5 1 7,c++,segmentation-fault,g++,cin,C++,Segmentation Fault,G++,Cin,我发现cin导致了这个错误,但我不知道为什么会出现这个错误以及如何修复它。 这是我的全部代码: #include <bits/stdc++.h> #define FOR(i, n) for (int i = 0; i < (n); i++) using ll = long long; using pii = std::pair<int, int>; using namespace std; struct Edge { int end, weight;

我发现cin导致了这个错误,但我不知道为什么会出现这个错误以及如何修复它。 这是我的全部代码:

#include <bits/stdc++.h>
#define FOR(i, n) for (int i = 0; i < (n); i++)
using ll = long long;
using pii = std::pair<int, int>;
using namespace std;

struct Edge {
    int end, weight;
    Edge(int e, int w): end(e), weight(w) {}
};

struct State {
    int node, time, cnt;

    bool operator<( State &rhs ) const {
        return time < rhs.time;
    }
};

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    int n, m, start, end;
    vector< State > last;
    vector< Edge > edges[10001];
    queue< State > q;

    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        edges[a].push_back(Edge(b, c));
    }
    cin >> start >> end;

    q.push({start, 0, 0});

    while (!q.empty()) {
        State cur = q.front();  q.pop();

        for (Edge e: edges[cur.node])
            q.push({e.end, cur.time + e.weight, cur.cnt + 1});

        if (cur.node == end)
            last.push_back(cur);
    }

    sort(last.begin(), last.end());
    cout << last.back().time << endl << last.back().cnt;

    return 0;
}
#包括
#定义(i,n)FOR(int i=0;i<(n);i++)
使用ll=长;
使用pii=std::pair;
使用名称空间std;
结构边{
内端,重量;
边(int e,int w):结束(e),权重(w){}
};
结构状态{
int节点,时间,cnt;
布尔算子;
向量<边>边[10001];
队列q;
cin>>n>>m;
对于(int i=0;i>a>>b>>c;
边[a]。推回(边(b,c));
}
cin>>开始>>结束;
q、 推送({start,0,0});
而(!q.empty()){
状态cur=q.front();q.pop();
对于(边e:边[cur.node])
q、 推送({e.end,cur.time+e.weight,cur.cnt+1});
if(cur.node==end)
最后,向后推(cur);
}
排序(last.begin(),last.end());

我认为应该用
m
代替
n

for (int i = 0; i < m; i++) {
    int a, b, c;
    cin >> a >> b >> c;
    edges[a].push_back(Edge(b, c));
}
for(int i=0;i>a>>b>>c;
边[a]。推回(边(b,c));
}

请不要将竞赛网站用作教学或学习资源。它们所教的只是如何编写其他地方无法使用的坏代码。你问题中的代码显示了许多坏习惯的例子。如果你试图在面试中提交这样的代码,那么它将立即被拒绝。
使用ll=long;
--Th现在是C++中的一些东西,叫做“代码>”,“It64”,“代码”。不需要像这样的疯狂别名。然后,代码>矢量>边>边[10001 ];< /C> > 10001个向量。看起来你应该使用<代码> STD::图边< /代码>。@有些程序员是令人惊讶的,那么我应该在哪里学习编写一个好代码?