Before going to learn about the shrink_to_fit() function. Lets have a look on these two terms −
The shrink_to_fit() function instructs the vector container to shrink its capacity to its size. In other words, the capacity will become equal to the actual number of elements that are contained inside the vector container.
SyntaxFollowing is the syntax for C++ vector::shrink_to_fit() Function −
void shrink_to_fit();Parameters
It doesn't accept any kind of parameter.
Example 1Let's consider the following example, where we are going to use shrink_to_fit() function.
#include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v(128); cout << "Initial capacity = " << v.capacity() << endl; v.resize(25); cout << "Capacity after resize = " << v.capacity() << endl; v.shrink_to_fit(); cout << "Capacity after shrink_to_fit = " << v.capacity() << endl; return 0; }Output
When we compile and run the above program, this will produce the following result −
Initial capacity = 128 Capacity after resize = 128 Capacity after shrink_to_fit = 25Example 2
Considering the another scenario, where we are going to take an string type and applying shrink_to_fit() function.
#include <iostream> #include <vector> using namespace std; int main(void) { vector<string> myvector(50); cout << "Initial capacity = " << myvector.capacity() << endl; myvector.resize(13); cout << "Capacity after resize = " << myvector.capacity() << endl; myvector.shrink_to_fit(); cout << "Capacity after shrink_to_fit = " << myvector.capacity() << endl; return 0; }Output
On running the above program, it will produce the following result −
Initial capacity = 50 Capacity after resize = 50 Capacity after shrink_to_fit = 13Example 3
In the following example, we are going to use push_back() function to insert the value and then applying the shrink_to_fit() function.
#include <iostream> #include <vector> using namespace std; void print_vector(vector<int> myvector){ for(int x: myvector) cout << x << " "; } int main(){ vector<int> myvector; myvector.push_back(11); myvector.push_back(22); myvector.push_back(33); cout << "Actual vector: "; print_vector(myvector); cout << endl; cout << "Capacity of vector is: " << myvector.capacity()<<endl; myvector.resize(2); cout << "After Resize(2): "; print_vector(myvector); cout << endl; cout << "Capacity of vector is: " << myvector.capacity()<<endl; myvector.shrink_to_fit(); cout << "after using shrink_to_fit() fuction vector capacity is: "<<myvector.capacity(); return 0; }Output
When we execute the above program, it will produce the following result −
Actual vector: 11 22 33 Capacity of vector is: 4 After Resize(2): 11 22 Capacity of vector is: 4 after using shrink_to_fit() fuction vector capacity is: 2
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4