Choice between vector::resize() and vector::reserve()
c++, memory-management, stdvector
Solution
The two functions do vastly different things!
The `resize()` method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect the `size()`, iteration will go over all those elements, push_back will insert after them and you can directly access them using the `operator[]`.
The `reserve()` method only allocates memory, but leaves it uninitialized. It only affects `capacity()`, but `size()` will be unchanged. There is no value for the objects, because nothing is added to the vector. If you then insert the elements, no reallocation will happen, because it was done in advance, but that's the only effect.
So it depends on what you want. If you want an array of 1000 default items, use `resize()`. If you want an array to which you expect to insert 1000 items and want to avoid a couple of allocations, use `reserve()`.
EDIT: Blastfurnace's comment made me read the question again and realize, that in your case the correct answer is don't preallocate manually. Just keep inserting the elements at the end as you need. The vector will automatically reallocate as needed and will do it more efficiently than the manual way mentioned. The only case where `reserve()` makes sense is when you have reasonably precise estimate of the total size you'll need easily available in advance.
EDIT2: Ad question edit: If you have initial estimate, then `reserve()` that estimate. If it turns out to be not enough, just let the vector do it's thing.
Problem
I am pre-allocating some memory to my a `vector` data member. Example: ``` class A { vector<string> t_Names; public: A () : t_Names(1000) {} }; ``` At some point in time, if the `t_Names.size()` equals `1000`, I intend to increase the size by `100`. Once it reaches `1100`, increase it by `100` and so on. Which do I choose out of `vector::resize()` and `vector::reserve()`? Is there any better choice in this kind of scenario? Edit: I have sort of precise estimate for the `t_Names`. I estimate it to be around `700` to `800`. However in certain (seldom) situations, it can grow more than `1000`.