[SOLVED] What is best to insert several values at the end of a std::vector?


To add elements to a std::vector<int> v is it better to do:

// Read and manipulate a, b, c triplet as ints.
// Potentially also: v.reserve(v.size() + 3); or trust vector growth policy?


v.insert(v.end(), {a, b, c});

from a performance point of view (assuming we are always going to insert triplets that are different everytime and a large unfixed number of them, say 1 million triplets)? Thanks for tips.


First of all, doing v.reserve(v.size() + 3); in a loop is generally a very bad idea since it will certainly cause a new reallocations for each iteration. For example, both Clang and GCC with the libstdc++ and libc++ actually do a linear number of reallocations (see here, here or even there). Here is a quote from cppreference:

Correctly using reserve() can prevent unnecessary reallocations, but inappropriate uses of reserve() (for instance, calling it before every push_back() call) may actually increase the number of reallocations (by causing the capacity to grow linearly rather than exponentially) and result in increased computational complexity and decreased performance. For example, a function that receives an arbitrary vector by reference and appends elements to it should usually not call reserve() on the vector, since it does not know of the vector’s usage characteristics.
When inserting a range, the range version of insert() is generally preferable as it preserves the correct capacity growth behavior, unlike reserve() followed by a series of push_back()s.
reserve() cannot be used to reduce the capacity of the container; to that end shrink_to_fit() is provided.

When it comes to insert VS push_backs, insert should be slightly better than many push_back because the capacity check can be done only once as opposed to multiple push_backs. That being said, the performance difference is very dependent of the standard library implementation.

Answered By – Jérôme Richard

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *