Question

This is the vector I created;

std::vector<std::vector<Vertex*>*> Vertices;

And I'm having trouble figuring out how to push back the std::vector<Vertex*> into the outer vector.

So what im kind of trying to do is:

Vertices.push_back(new vector().push_back(new Vertex()));

but I'm not sure what the right way to do it is. Hope you people get the idea.

Was it helpful?

Solution

Although it is sometimes OK to make a vector of pointers (preferably, smart pointers), it is never a good idea to make a vector of pointers to vectors: this complicates your memory management for no good reason.

The best solution is to use a vector of vertex objects, like this:

std::vector<std::vector<Vertex> > vertices;

This would let you push back like this:

vector<Vertex> vv;
vv.push_back(Vertex(...));
vertices.push_back(vv);

If you want a vector of descendants of Vertex with polymorphic behavior, use a vector of vectors of pointers:

std::vector<std::vector<Vertex*> > vertices;
...
vector<Vertex*> vv;
vv.push_back(new Vertex(...));
vertices.push_back(vv);

Note that if you do this, you are on the hook for freeing the Vertex objects inside the vector. A better solution would be using smart pointers - say, unique_ptr, like this:

std::vector<std::vector<unique_ptr<Vertex> > > vertices;

unique_ptr would take care of freeing Vertex objects automatically.

OTHER TIPS

You can't do it in a single line. But you can do it in 4;

std::vector<std::vector<Vertex*>*> Vertices;
std::vector<Vertex*> * vec = new std::vector<Vertex*>;
vec.push_back(new Vertex()); // fill the inner vector as many times as you need
Vertices.push_back(vec);

But why you would want to do that? You will leak memory if you won't call delete for each element of the outer vector, but before doing that you will need to call delete on every Vertex* in inside vectors.

Edit: for a better way of storing Vertex without leaking memory look at dasblinkenlight's answer.

It is doable. For example, try:

std::vector<std::vector<Vertex*>> Vertices;
Vertices.push_pack(std::vector<Vertex*>());
Vertices.back().push_back(new Vertex[8]);

Following this code, you do not need to use any extra memory. To access or modify the element located in the i'th member of first vector, and j'th member of the second vector, and the 6th member of the array, you can use:

Vertices.at(i).at(j)[6];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top