reserve
reserves memory for growing the vector, with out changing it's size()
. So in your case, [4]
is still an invalid index.
While the vector will grow to a size as needed, there's a significant tradeoff between growing in large vs. small chunks: large chunks make expensive reallocations and copies less common, but also waste memory.
reserve(10)
reserves memory so you can e.g. push_back
10 elements without having a reallocation.
When to use: if you are adding elements to a vector in multiple steps, and you know ahead the amount of elements - or even if you have a good guess - use reserve
to prepare the vector for accepting that many elements, and reduce the number of allocations necessary.
The amount reserved is called capacity - and can be queried using .capacity()
.