Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::vector::resize() ever reallocate when new size is smaller than current size? [duplicate]

Possible Duplicate:
std::vector resize downward

If I resize() an std::vector to some size smaller than its current size, is it possible that the vector will ever allocate new memory?

This is important to me for performance reasons.

like image 791
Alex Flint Avatar asked Jan 14 '13 14:01

Alex Flint


People also ask

What happens to the elements in a vector when it is resized to something bigger smaller?

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.

Does resize change capacity?

Calling resize() with a smaller size has no effect on the capacity of a vector . It will not free memory.

What does std :: vector resize do?

vector::resizeResizes the container to contain count elements. If the current size is greater than count, the container is reduced to its first count elements.

Can you change vector size?

Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. The function alters the container's content in actual by inserting or deleting the elements from it.


2 Answers

No, resizeing to a smaller size will never reallocate.

In case the container shrinks, all iterators, pointers and references to elements that have not been removed remain valid after the resize and refer to the same elements they were referring to before the call.

(From here)

Given that, we can be sure that a reallocation cannot have happened.

like image 119
Chowlett Avatar answered Sep 17 '22 19:09

Chowlett


resize() when reducing only changes the logical size. Others have already answered this, so I am adding nothing here. The purpose of this is to optimise for speed, as it does not need to reallocate or move any data.

However when you want to optimise for memory usage, C++11 has introduced a further function shrink_to_fit() that you may call after your resize() (or even at any other time) which will actually ensure you don't pay for any memory you don't want.

like image 44
CashCow Avatar answered Sep 17 '22 19:09

CashCow