Reputation: 67
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.
Upvotes: 2
Views: 29648
Reputation: 726977
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(std::move(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(std::move(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, std::unique_ptr
, like this:
std::vector<std::vector<std::unique_ptr<Vertex>>> vertices;
std::unique_ptr
would take care of freeing Vertex
objects automatically.
Upvotes: 7
Reputation: 1
u could try this way for
enter image description here for inserting the values of vector2 at the back of the vector1 .
std::vector vector1 = {1, 2, 3}; std::vector vector2 = {4, 5, 6};
vector1.insert(vector1.end(), vector2.begin(), vector2.end());
enter image description here
Upvotes: -1
Reputation: 1
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];
Upvotes: 0
Reputation: 4195
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.
Upvotes: 1