English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Deque resize() Usage and Example

C++ Deque (Double-ended Queue)

C ++ The Deque resize() function changes the size of the double-ended queue container to the size given in the parameter, that is, changes the size of the deque.

The following are the conditions:

If n is greater than the size of the container, the container size can be expanded to n elements by inserting new elements in the extended space.

If n is less than the size of the container, the container will be reduced to n elements, and all elements except n elements will be deleted.

Where, n is the new size of the container given in the parameter.

Syntax

void resize(int n, value_type val);

Parameter

n: This is the new container size.

val: The new value to be added in the extended space.

Return value

It does not return any value.

Example1

Let's look at a simple example, when n is less than the size of the container.

#include <iostream>
#include<deque>
using namespace std;
int main()
{
  deque<int> d={100,200,300,400,500};
  d.resize(3);
  for(int i=0; i<d.size(); i++)
  {
      cout << d[i];
      cout << " ";
  }
  return 0;
}

Output:

100 200 300

In this example, the resize() function adjusts the container size to3. Therefore, the element at3all elements except the n elements.

Example2

Let's look at a simple example, when n is greater than the size of the container.

#include <iostream>
#include<deque>
using namespace std;
int main()
{
  deque<string> d={"C","C"}++,"java",".Net","python"};
  d.resize(7,"rust");
  for(int i=0; i<d.size(); i++)
  {
      cout << d[i];
      cout << " ";
  }
 return 0;
}

Output:

C C++ java .Net python rust rust

In this example, the resize() function adjusts the container size to7Therefore, the newly added space will insert the new element "rust".

C++ Deque (Double-ended Queue)