# 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 of vector::shrink_to_fit() function**

vector::shrink_to_fit();

**Parameter(s):** none – It accepts nothing.

**Return value:** void – It returns nothing.

**Example:**

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()

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.