what's the best practice to change its size to 0 and capacity to N(a given number)? My direct idea is: ...
Your direct idea is correct, and the simplest option. Although to be pedantic, reserve
changes capacity to greater or equal to the given number; not guaranteed to be equal (but all implementations I've tested do allocate exactly the given amount if the previous capacity was less).
So I'm wondering how to avoid reallocating when the origin capacity is larger than the given N?
By using a standard library implementation that has chosen to not deallocate the memory on a call to clear
(i.e. any standard conforming implementation, as indicated by the answer here).
Another approach to guarantee (although, it appears that this is not necessary as the above should be guaranteed, despite the weak wording on cplusplus.com) no reallocation (in the case N > t.capacity()
): Since the vector contains simple integers, and you appear to know how many elements there will be (as you know to reserve), you could simply call t.resize(N)
(to remove extra elements in case size was greater) without clearing the vector, and then proceed to overwrite the existing elements, rather than push new ones.
Of course, this means that you won't be able to observe the number of elements that have been overwritten, so this approach is not applicable for all use cases. It's fine if you simply want to fill the vector with a simple loop.
You might possibly want to reserve before resizing if the new size might be greater than the old, and you desire to not over-allocate. This is because most implementations allocate exact amount on reserve (as I mentioned) but use multiplication strategy on resize (neither of these behaviours are guaranteed as far as I know, but the implementations I've used have been consistent with this behaviour).