简体   繁体   中英

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?

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.

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.

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 Neighbor s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM