From this answer:
One place where you can run into a performance issue, is not sizing the vector correctly to begin with.
So, how does one size a vector correctly when it is a property of a class? Is there a (best) way to set the capacity of vector (at initialisation)?
Yes there is. See the reserve method. It will request that a vector’s capacity be at least enough to contain the number of elements sent as its argument. If you can anticipate an upper bound on the number of items that you want to store in a vector, then you can reserve that amount of space in your vector.
Example from the above link –
You will see that as you add more elements to the
foovector, its capacity keeps increasing, but in the second case, since it has already reserved 100 element’s space, the capacity is changed only once.Here is a running example.