Home »
C++ STL
vector::shrink_to_fit() function with example in C++ STL
C++ STL vector::shrink_to_fit() function: Here, we are going to learn about the shrink_to_fit() function of vector header in C++ STL with example.
Submitted by Radib Kar, on May 17, 2019
C++ vector::shrink_to_fit() function
vector::shrink_to_fit() is a library function of "vector" header, which is used to reduce capacity to fit size. Refer to example to understand in details.
This may lead to reallocation, but elements don't alter.
Note: To use vector, include <vector> header.
Syntax
Syntax of vector::shrink_to_fit() function
vector::shrink_to_fit();
Parameter(s)
none – It accepts nothing.
Return value
void – It returns nothing.
Sample Input and Output
Input:
//capacity is initialized to be 100
vector<int> arr(50);
arr.capacity() =50
Resize:
//doesn't change capacity though
arr.resize(10);
arr.capacity() =50
shrink_to_fit:
//changes capacity as per resize,
//thus this practically reduced the capacity
arr.shrink_to_fit();
arr.capacity() =10
C++ program to demonstrate example of vector::shrink_to_fit() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arr(50); //capacity is initialized to be 100
cout << "...capacity of the vector: " << arr.capacity() << "...\n";
arr.resize(10); //doesn't change capacity though
cout << "...After resizing...\n";
cout << "capacity of the vector: " << arr.capacity() << "\n";
arr.shrink_to_fit(); //changes capacity as per resized vector
cout << "...After using shrink_to_fit...\n";
cout << "capacity of the vector: " << arr.capacity() << "\n";
return 0;
}
Output
...capacity of the vector: 50...
...After resizing...
capacity of the vector: 50
...After using shrink_to_fit...
capacity of the vector: 10
Reference: C++ vector::shrink_to_fit()