Reputation: 465
When reading from vector I put values in I got zero size. I have:
class Graph {
public:
vector<Vertex> vertices;
};
class Vertex {
public:
vector<int> adjacentVertices;
};
In my load method then:
int vertices, edges;
cin >> vertices >> edges;
Graph mainGraph;
mainGraph.vertices.reserve(static_cast<unsigned int>(vertices));
int tmp1, tmp2;
for (int i = 0; i < edges; i++) {
cin >> tmp1 >> tmp2;
mainGraph.vertices[tmp1].adjacentVertices.push_back(tmp2);
cout << mainGraph.vertices[tmp1].adjacentVertices.size(); //PRINTS NUMBERS -> SEEMS OKAY
}
cout << mainGraph.vertices.size(); //IS ZERO???
for(const Vertex &v : mainGraph.vertices){ //CRASHES
cout << v.adjacentVertices.size();
}
I bet this is very stupid but what am I missing? I read the vector will self construct itself upon use if no special constructor is needed.
Upvotes: 2
Views: 1435
Reputation: 917
That happened because you're trying to manage the size of your vectors manually. Let the STL do all the work dynamically:
Graph mainGraph;
int edge;
while (cin >> edge)
{
Vertex newVertex;
newVertex.adjacentVertices.push_back(edge);
mainGraph.vertices.push_back(std::move(newVertex));
}
for(const Vertex &v : mainGraph.vertices)
cout << v.adjacentVertices.size();
Upvotes: 0
Reputation: 73366
Change this:
mainGraph.vertices.reserve(static_cast<unsigned int>(vertices));
to this:
mainGraph.vertices.resize(static_cast<unsigned int>(vertices));
since with reserve() the cells of the vector are not created, which can be done though with resize().
As a result, in your code, you invoke Undefined Behavior (UB), when you do mainGraph.vertices[tmp1]
, since you attempt to access an object that has not been constructed!
Upvotes: 8
Reputation: 21927
reserve
does not change the size of the vector
or construct items. It only allocates memory that will be reserved for when you do add elements.
Your call to mainGraph.vertices[tmp1]
is undefined as it is accessing raw memory.
Instead of reserve
, use resize
to both allocate and construct items.
Upvotes: 7