Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


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 below example, 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<<"Now, MyArray 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 

Now, MyArray contains: 100 100 100 100 100 

❮ C++ - Array