【问题标题】:C++ How to properly do the assignment of a 2D vector of a user defined classC ++如何正确分配用户定义类的二维向量
【发布时间】:2018-04-22 23:12:28
【问题描述】:

我正在尝试使用 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 类中没有动态分配的成员,我认为将使用默认构造函数和默认值,执行此分配不会有任何问题,但在运行时出现分段错误。
错误是由于这一行:graph[u].push_back(Vertex(v));
我检查了访问graph[u]没有问题。调用push_back 方法时会报错。
我认为这应该有效,但我不知道为什么它没有。有人可以帮我解决这个问题吗?

如果需要,我的 Vertex 类:

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;
};

【问题讨论】:

    标签: c++ stdvector assignment-operator


    【解决方案1】:

    您对graph=vector&lt;vector&lt;Vertex&gt;&gt;(n,vector&lt;Vertex&gt;()); 有未定义的行为。你没有初始化n。试试这样:

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

    【讨论】:

    • 也没有检查以确保 u 和 v 介于 0 和 n-1 之间。
    • 哦,我的错。我在收到输入后添加了graph=vector&lt;vector&lt;Vertex&gt;&gt;(n,vector&lt;Vertex&gt;()); 行,但这次又引发了另一个错误。
    猜你喜欢
    • 2015-06-10
    • 2023-03-10
    • 1970-01-01
    • 2016-08-11
    • 2011-06-29
    • 2017-12-26
    • 2013-11-30
    • 1970-01-01
    • 2019-06-07
    相关资源
    最近更新 更多