C++ Standard Library C++ STL Library

C++ <deque> - shrink_to_fit() Function



The C++ deque::shrink_to_fit function is used to change the deque capacity and makes it equal to the size of the deque. This may cause a reallocation, but there will be no effect on deque size and all elements of the deque will be unaltered.

Syntax

void shrink_to_fit();

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n) at most.

Example:

In the example below, the deque::shrink_to_fit function is used to change the deque capacity and makes it equal to the size of the deque MyDeque.

#include <iostream>
#include <deque>
using namespace std;
 
int main (){
  deque<string> MyDeque (50);

  cout<<"MyDeque size is: "<<MyDeque.size();

  MyDeque.resize(10);
  cout<<"\nMyDeque size is: "<<MyDeque.size();

  MyDeque.shrink_to_fit();
  return 0;
}

The output of the above code will be:

MyDeque size is: 50
MyDeque size is: 10

❮ C++ <deque> Library