C++ Deque::shrink_to_fit() Function



The C++ std::deque::shrink_to_fit() function is used to reduce the capacity of a deque to fit its size, freeing unused memory. This function is non-binding, meaning it serves as a request to the implementation and may not always result in reduced capacity. It has no effect on the size or elements of the container.

Syntax

Following is the syntax for std::deque::shrink_to_fit() function.

void shrink_to_fit();

Parameters

It does not accept any parameter.

Return value

This function does not return anything.

Exceptions

This function never throws exception.

Time complexity

The time complexity of this function is Constant i.e. O(1)

Example

In the following example, we are going to consider the basic usage of the shrink_to_fit() function.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a;
    for (int x = 0; x < 10; ++x) {
        a.push_back(x);
    }
    std::cout << "Deque size before shrink_to_fit(): " << a.size() << std::endl;
    a.shrink_to_fit();
    std::cout << "Deque size after shrink_to_fit(): " << a.size() << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Deque size before shrink_to_fit(): 10
Deque size after shrink_to_fit(): 10

Example

Consider the following example, where we are going to use the clear and shrink on the deque.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a;
    for (int x = 0; x < 5; ++x) {
        a.push_back(x);
    }
    a.clear();
    a.shrink_to_fit();
    std::cout << "Deque size after clear and shrink: " << a.size() << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Deque size after clear and shrink: 0

Example

In the following example, we are going to use the shrink after resizing.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a;
    for (int x = 0; x < 10; ++x) {
        a.push_back(x);
    }
    a.resize(5);
    a.shrink_to_fit();
    std::cout << "Deque capacity after resizing and shrink: " << a.size() << std::endl;
    return 0;
}

Output

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

Deque capacity after resizing and shrink: 5
deque.htm
Advertisements