I read on the Internet that if you are clearing a std::vector
repetitively (in a tight loop), it might be better to use resize(0)
instead of clear()
, as it may be faster. I am not sure about this. Does anyone have a definitive answer to this?
The standard mandates that the capacity does not change with a clear as reserve guarantees that further adding of elements do not relocate until the requested capacity is reached.
vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.
Using vector::clear function So, we're left with a vector of size 0 but some finite capacity. Starting with C++11, we can call the vector::shrink_to_fit function after clear() , which reduces the vector's capacity to fir the size. It works by “requesting” a reallocation on the vector.
The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector. If val is specified then new elements are initialed with val.
I assume you mean resize(0)
instead of setsize
, and calling that instead of clear()
, and that you're talking about std::vector
. IIRC a recent answer discussed this (can't find the link), and on modern STL implementations, clear()
is likely identical to resize(0)
.
Previously clearing a vector might have freed all its memory (ie. its capacity also falls to zero), causing reallocations when you start adding elements again, in contrast to resize(0)
keeping the capacity so there are fewer reallocations. However, I think in modern STL libraries there is no difference. If you're using an old STL implementation, or you're just paranoid, resize(0)
might be faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With