push_back an object into vector

The second example has a memory leak.

If what you want is just a “fill” function then setOfVertices.insert(setOfVertices.end(), 10, Vertex()); is good enough.

However, if what you want instead is insert different Vertex objects then

// Make sure only a single memory allocation takes place.
setOfVertices.reserve(setOfVertices.size() + 10);

for (int i = 0; i < 10; i++)
    setOfVertices.push_back(Vertex(i));

Leave a Comment