C++ vector shrink_to_fit() Function
Example
Free the memory that a vector does not use:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.reserve(100);
cars.shrink_to_fit();
cout << "Size: " << cars.size();
Definition and Usage
The shrink_to_fit() function asks the vector to free the memory it does not use, so that the capacity becomes the same as the size.
The size and the elements do not change. This is only a request, so C++ does not guarantee that the memory is freed.
The shrink_to_fit function is defined in the <vector> header file.
Note: The exact capacity depends on the compiler, so the example does not print it.
Syntax
vector.shrink_to_fit();
Parameter Values
None.
Technical Details
| Returns: | Nothing (void). |
|---|
Related Pages
Read more about vectors in our Vector Tutorial.