Search code examples
c++stdvectorassignment-operator

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


I am trying to generate a graph by using 2D vector in which I will place instances of the Vertex object that I defined.

Related code is here:

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

Instead of initializing the graph during the declaration, I wanted to generate the graph by using assignment according to the n value that I will get. Since there is no dynamically allocated member in Vertex class, I thought the default constructors and default values will be used and there wouldn't be any problem in performing this assignment but in the run-time I get a segmentation fault.
Error is due to this line: graph[u].push_back(Vertex(v));
I checked there is no problem in accessing graph[u]. It gives the error when calling push_back method.
I thought this should have worked but I couldn't figure out why it didn't. Can somebody help me fix this?

In case it will be needed, my 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;
};

Solution

  • You are have the undefined behavior for graph=vector<vector<Vertex>>(n,vector<Vertex>());. You not initialized n. Try like this:

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