A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/vector-shrink_to_fit-function-in-c-stl/ below:

Vector shrink_to_fit() in C++ STL

Vector shrink_to_fit() in C++ STL

Last Updated : 11 Jul, 2025

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;
}

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.



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