Open In App

Vector shrink_to_fit() in C++ STL

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, vector shrink_to_fit() is a built-in function used to reduce the capacity of the vector to fit its size and destroys all elements beyond the size. In this article we will learn about vector shrink_to_fit() in C++.

Let’s take a quick look at an example that illustrates vector shrink_to_fit() method:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v(10);
    v.resize(5);

    // Shrink capacity of vector
    v.shrink_to_fit();

    cout << v.capacity();
    return 0;
}

Output
5

This article covers the syntax, usage, and common examples of vector shrink_to_fit() method in C++:

Syntax of vector shrink_to_fit()

The vector shrink_to_fit() is the member method of std::vector class defined inside <vector> header file.

v.shrink_to_fit();

This function does not require any parameter nor returns any value.

Example of vector shrink_to_fit()

The following example demonstrates the use of vector shrink_to_fit() function for different cases:

Reduce Capacity of Vector

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v(11);
    cout << "Initial Capacity: " << v.capacity() << endl;

    v.resize(7);

    // Shrink capacity of vector
    v.shrink_to_fit();

    cout << "Final Capacity: " << v.capacity();
    return 0;
}

Output
Initial Capacity: 11
Final Capacity: 7

Explanation: Initially capacity of vector is 11, but after applying vector resize(), decrease the size of vector to 7 but not capacity. So, to decrease the capacity of vector we use vector shrink_to_fit() which makes capacity equal to size of vector.


Next Article
Article Tags :
Practice Tags :

Similar Reads