VOOZH about

URL: https://www.geeksforgeeks.org/cpp/vector-shrink_to_fit-function-in-c-stl/

⇱ Vector shrink_to_fit() in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:


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


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.

Comment
Article Tags: