Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between std::resize(n) and std::shrink_to_fit in C++?

I came across these statements:

resize(n) – Resizes the container so that it contains ‘n’ elements.
shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.

Is there any significant difference between these functions? they come under vectors in c++

like image 618
Sneha Sridharan Avatar asked Feb 25 '20 18:02

Sneha Sridharan


1 Answers

Vectors have two "length" attributes that mean different things:

  • size is the number of usable elements in the vector. It is the number of things you have stored. This is a conceptual length.
  • capacity is how many elements would fit into the amount of memory the vector has currently allocated.

capacity >= size must always be true, but there is no reason for them to be always equal. For example, when you remove an element, shrinking the allocation would require creating a new allocation one bucket smaller and moving the remaining contents over ("allocate, move, free").

Similarly, if capacity == size and you add an element, the vector could grow the allocation by one element (another "allocate, move, free" operation), but usually you're going to add more than one element. If the capacity needs to increase, the vector will increase its capacity by more than one element so that you can add several more elements before needing to move everything again.

With this knowledge, we can answer your question:

  • std::vector<T>::resize() changes the size of the array. If you resize it smaller than its current size, the excess objects are destructed. If you resize it larger than its current size, the "new" objects added at the end are default-initialized.
  • std::vector<T>::shrink_to_fit() asks for the capacity to be changed to match the current size. (Implementations may or may not honor this request. They might decrease the capacity but not make it equal to the size. They might not do anything at all.) If the request is fulfilled, this will discard some or all of the unused portion of the vector's allocation. You'd typically use this when you are done building a vector and will never add another item to it. (If you know in advance how many items you will be adding, it would be better to use std::vector<T>::reserve() to tell the vector before adding any items instead of relying on shrink_to_fit doing anything.)

So you use resize() to change how much stuff is conceptually in the vector.

You use shrink_to_fit() to minimize the excess space the vector has allocated internally without changing how much stuff is conceptually in the vector.

like image 148
cdhowie Avatar answered Sep 28 '22 06:09

cdhowie