Ritoban Roy Chowdhury
Ritoban Roy Chowdhury

Reputation: 89

C++ crashing:push_back on nested vectors

#include <iostream>
#include <vector>

using namespace std;

struct Neighbor
{
    int index;
    int weight;
    Neighbor(int, int);
};

Neighbor::Neighbor(int index, int weight)
{
    Neighbor::index = index;
    Neighbor::weight = weight;
}

void addEdge(vector<vector<Neighbor> > &graph, int v1, int v2, int weight)
{
    graph[v1].push_back(Neighbor(v2, weight));
    graph[v2].push_back(Neighbor(v1, weight));
}

int main()
{
    vector<vector<Neighbor> > graph;
    vector<vector<Neighbor> > graphIterator;
    graph[0].push_back(Neighbor(1, 5));
    graph[0].push_back(Neighbor(3, 3));
    graph[0].push_back(Neighbor(4, 2.5));

    graph[1].push_back(Neighbor(0, 5));
    graph[1].push_back(Neighbor(2, 3));

    graph[2].push_back(Neighbor(1, 3));
    graph[2].push_back(Neighbor(4, 2.5));
    graph[2].push_back(Neighbor(3, 5));

    graph[3].push_back(Neighbor(0, 3));
    graph[3].push_back(Neighbor(2, 5));
    graph[3].push_back(Neighbor(4, 2.5));

    graph[4].push_back(Neighbor(0, 2.5));
    graph[4].push_back(Neighbor(2, 2.5));
    graph[4].push_back(Neighbor(3, 2.5));

    return 0;
}

The above is my code, that seems to be crashing when run. Although declaring the vector graph seems to work fine, the program crashes even when I include my first push_back statement. Can someone advise me?

Upvotes: 1

Views: 1469

Answers (3)

Kevin Pe&#241;a
Kevin Pe&#241;a

Reputation: 782

Here

vector<vector<Neighbor> > graph;
/*...*/
graph[0].push_back(Neighbor(1, 5));

You are accessing to graph[0] wich has not been created. This is best visualized if you create a typedef to vector<Neighbor>.

typedef vector<Neighbor> NeighborVec;
vector<NeighborVec> graph;
NeighborVec& firstVec = graph[0];

You can see clearly that although graph has been initialized graph[0] has not. You would need to do:

typedef vector<Neighbor> NeighborVec;
vector<NeighborVec> graph;
graph.push_back(NeighborVec());
NeighborVec& firstVec = graph[0];
firstVec.push_back(Neighbor(1, 5));

tl;dr:

You forgot to initialize the first level of your nested vector.

Upvotes: 1

Nick Matteo
Nick Matteo

Reputation: 4553

graph is created empty, then you try to access graph[0], … graph[4] which are not there.

You can initially declare it as vector<vector<Neighbor> > graph(5); so that it is initialized holding 5 empty vectors of Neighbors.

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172964

When graph[0].push_back(Neighbor(1, 5));, graph is still empty, it has no elements and graph[0] leads to UB.

You should add elements firstly, like:

graph.push_back(vector<Neighbor>()); // add one element
...

or

vector<vector<Neighbor> > graph(5); // construct vector with 5 elements

or

vector<vector<Neighbor> > graph;
graph.resize(5);                    // resize vector to contain 5 elements.

Upvotes: 5

Related Questions