C++ 如何正确分配用户定义的二维向量 class

C++ How to properly do the assignment of a 2D vector of a user defined class

我正在尝试使用 2D 向量生成图形,我将在其中放置我定义的 Vertex 对象的实例。

相关代码在这里:

...
vector<vector<Vertex>> graph;
Vertex start;
int q;
cin >> q;
for(int a0 = 0; a0 < q; a0++){
    int n;
    graph=vector<vector<Vertex>>(n,vector<Vertex>());
    int m;
    cin >> n >> m;
    for(int a1 = 0; a1 < m; a1++){
        int u;
        int v;
        cin >> u >> v;
        graph[u].push_back(Vertex(v));
        graph[v].push_back(Vertex(u));
    }
...
}
...
}

我不想在声明期间初始化图形,而是想根据我将获得的 n 值使用赋值来生成图形。由于 Vertex class 中没有动态分配的成员,我认为将使用默认构造函数和默认值,执行此分配不会有任何问题,但在 运行-time 我得到分段错误。
错误是由于这一行:graph[u].push_back(Vertex(v));
我检查了访问 graph[u] 没有问题。它在调用 push_back 方法时给出错误。
我认为这应该行得通,但我不明白为什么行不通。有人可以帮我解决这个问题吗?

如果需要,我的 Vertex class:

class Vertex
{
    public:
        Vertex()
        {
            value=0;
            distance=1000000;
            color=char('w');
        }
        Vertex(int x)
        {
            value=x;
            distance=1000000;
            color=char('w');
        }
        int value;
        int distance;
        char color;
};

您有 graph=vector<vector<Vertex>>(n,vector<Vertex>()); 的未定义行为。您没有初始化 n。像这样尝试:

int n = 10;
graph=vector<vector<Vertex>>(n,vector<Vertex>());