首页 > 解决方案 > 向量下标超出范围 MVS2013

问题描述

这是我用来查找图的 MST 的一些代码。我使用 scanf 在结构中输入边并将它们存储在具有边对象的向量中。我不明白为什么我会收到“向量下标超出范围错误”,因为我初始化了向量大小。

struct GraphEdge
{
    int x, y, weight;
    void readinput()
    {
        scanf("%d%d%d", &x, &y, &weight);

    }
    bool operator<(const GraphEdge &e) const
    {
        return weight < e.weight;
    }
};

int main()
{
    while (1)
    {
        int n, m;
        int total_weight = 0;
        scanf("%d%d", &n, &m);
        if (!n && !m)
            break;
        int res = 0;
        vector<GraphEdge> edge(m);
        for (int i = 0; i < edge.size(); i++)
        {
            edge[i].readinput();
            cout << edge[i].x << " " << edge[i].y << endl;
            res += edge[i].weight;
            //cout << i << endl;
        }
        sort(edge.begin(), edge.end());
        union_find uf;
        uf.init(n);
        int cnt = 0, mst = 0;
        for (int i = 0; cnt < n - 1 && i < m; i++)
        {
            if (uf.dstunion(edge[i].x, edge[i].y))
            {
                res -= edge[i].weight;
                cnt++;
                mst += edge[i].weight;
            }
        }
        printf("%d\n", res);

    }
    return 0;
}

标签: c++vector

解决方案


推荐阅读