Let’s
std::vector myVec;
myVec.reserve(10);
If I allocated only 5 elements, how can I regain memory allocated for other 5 elements?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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_fithttp://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:
This has the benefit of instantly destroying temporary at the end of the expression.