# Deque shrink_to_fit in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of deque::shrink_to_fit() function in C++ STL.

## What is Deque?

Deque is the Double Ended Queues that are the sequence containers which provides the functionality of expansion and contraction on both the ends. A queue data structure allow user to insert data only at the END and delete data from the FRONT. Let’s take the analogy of queues at bus stops where the person can be inserted to a queue from the END only and the person standing in the FRONT is the first to be removed whereas in Double ended queue the insertion and deletion of data is possible at both the ends.

## What is deque::shrink_to_fit()?

deque::shrink_to_fit() is an inbuilt function in C++ STL which is declared in <deque> header file. deque::shrink_to_fit() which shrinks the capacity of the deque container to a specified fit size and removes all the elements which are beyond the fit. This function is very helpful when we have the size issues, or a container is exceeding the specified size.

## Syntax

mydeque.shrink_to_fit();

The function requires no parameter.

## Return value

This function returns nothing.

## Example

Input: deque<int> mydeque = {10, 20 30, 40, 0, 0, 0};
mydeque.shrink_to_fit();
Output:
Size of the mydeque = 40

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
deque<int> Deque(50);
cout<<"Initial size of Deque is : " << Deque.size();
Deque.resize(40);
cout<<"\nDeque size after resizing it : " << Deque.size() << endl;
Deque.shrink_to_fit();
return 0;
}

## Output

If we run the above code it will generate the following output −

Initial size of Deque is : 50
Deque size after resizing it : 4

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
deque<int> Deque(10);
for (int i = 0; i <= 5; i++)
Deque[i] = i;
cout<<"Initial size of Deque is: " << Deque.size();
cout<<"\n Deque elements are: ";
for (int i = 0; i <= 7; i++)
cout << Deque[i] << " ";
Deque.resize(10);
cout << "\n After resizing deque size is : "<<Deque.size();
cout << "\n Deque elements are: ";
for (int i = 0; i < 10; i++)
cout << Deque[i] << " ";
Deque.shrink_to_fit();
return 0;
}

## Output

If we run the above code it will generate the following output −

Deque elements are: 0 1 2 3 4 5 0 0
After resizing deque size is : 10
Deque elements are: 0 1 2 3 4 5 0 0 0 0
Published on 05-Mar-2020 15:42:24