c++vectorpushback

C++ Push back a vector into a vector


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.


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(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.