Shibli
Shibli

Reputation: 6149

Regain memory allocated by reserve()

Let's

std::vector myVec;
myVec.reserve(10);

If I allocated only 5 elements, how can I regain memory allocated for other 5 elements?

Upvotes: 2

Views: 145

Answers (1)

111111
111111

Reputation: 16158

 std::vector<int> v(myVec);
 myVec.swap(v);

This will initialise a vector with the same amount of elements, however it should have only enough memory to hold them. Then it is swapped with the original, this should swap the data store (using a cheap pointer swap) and the oversized array will be destroyed.

or in C++11 you can use std::vector::shrink_to_fit

myVec.shrink_to_fit();

http://en.cppreference.com/w/cpp/container/vector/shrink_to_fit

If you have this, this is much preferred, although it is non binding (implementation dependant as to how much if any is removed), so if it is a really large type then make sure you profile your code to make sure it is removing them.

EDIT: as david suggested there is a shorthand for the first method if you do not have C++11 that is:

std::vector<int>(myVec).swap(myVec);

This has the benefit of instantly destroying temporary at the end of the expression.

Upvotes: 8

Related Questions