C++ Standard Library C++ STL Library

C++ <valarray> - resize() Function



The C++ valarray::resize function is used to change the size of valarray to count elements, and assigns val to each element. After resizing, the previous contents are lost. This functions invalidates all pointers and references to elements in the array.

Syntax

void resize (size_t count, T val = T());

Parameters

count Specify the new size of the valarray.
size_t is an unsigned integral type.
val Specify the value to initialize the new elements with.

Return Value

None.

Time Complexity

Depends on library implementation.

Example:

The example below shows the usage of valarray::resize function.

#include <iostream>
#include <valarray>
using namespace std;
 
int main (){
  valarray<int> varr = {10, 20};

  cout<<"1. varr contains: ";
  for(int i = 0; i < varr.size(); i++)
    cout<<varr[i]<<" ";

  //resizing the valarray 
  varr.resize(4);
  cout<<"\n2. varr contains: ";
  for(int i = 0; i < varr.size(); i++)
    cout<<varr[i]<<" ";

  //resizing the valarray and
  //assigning each element to 10
  varr.resize(5, 10);
  cout<<"\n3. varr contains: ";
  for(int i = 0; i < varr.size(); i++)
    cout<<varr[i]<<" ";

  return 0;
}

The output of the above code will be:

1. varr contains: 10 20 
2. varr contains: 0 0 0 0 
3. varr contains: 10 10 10 10 10 

❮ C++ <valarray> Library

5