Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector clear vs. resize

Tags:

c++

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?

like image 755
SWKK Avatar asked Apr 29 '10 16:04

SWKK


People also ask

Does clear change vector size?

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.

What does vector Clear () do?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.

Does vector clear reduce capacity?

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.

What happens when a vector is resized?

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.


1 Answers

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.

like image 73
AshleysBrain Avatar answered Oct 24 '22 17:10

AshleysBrain