C++ Standard Library C++ STL Library

C++ <array> - fill() Function



The C++ array::fill function is used to set a given value to all elements of the array.

Syntax

void fill (const value_type& val);

Parameters

val Specify value to fill the array with.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the array::fill function is used to set a given value to all elements of the array MyArray.

#include <iostream>
#include <array>
using namespace std;
 
int main (){
  array<int, 5> MyArray{10, 20, 30, 40, 50};
 
  cout<<"MyArray contains: ";
  for(int i=0; i < MyArray.size(); i++)
    cout<<MyArray[i]<<" "; 

  //set value of all elements of the array to 100
  MyArray.fill(100);

  cout<<"\nMyArray contains: ";
  for(int i=0; i < MyArray.size(); i++)
    cout<<MyArray[i]<<" ";

  return 0;
}

The output of the above code will be:

MyArray contains: 10 20 30 40 50 
MyArray contains: 100 100 100 100 100 

❮ C++ <array> Library