C++ Deque::resize() Function



The C++ std::deque::resize() function is used to adjust the size of the deque. If the new size is greater than the current size, the deque is expanded and the new elements are added to the end. Similarly, if the new size is smaller, the deque is truncated, and the excess elements at the end are removed.

This function has 2 polymorphic variants: with using the default and the value version (you can find the syntaxes of all the variants below).

Syntax

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

void resize (size_type n);
or
void resize (size_type n, const value_type& val);

Parameters

  • n − It indicates the size of the new container.
  • val − It indicates the initial value for container elements.

Return value

This function does not return anything.

Exceptions

If reallocation fails then bad_alloc exception is thrown.

Time complexity

The time complexity of this function is Linear i.e. O(n)

Example

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

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a;
    a.resize(4);
    for (auto& elem : a) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

0 0 0 0

Example

Consider the following example, where we are going to resize the deque and assign the value.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> x;
    x.resize(3, 'A');
    for (auto& elem : x) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

Following is the output of the above code −

A A A

Example

Let's look at the following example, where we are going to decreasing the size of the deque using resize() function.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a{1,12,23,34,45,56};
    a.resize(4);
    for (auto& elem : a) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

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

1 12 23 34 
deque.htm
Advertisements