C++ Array::fill() Function



The C++ std::array::fill() function is used to assign a specific value to all elements of a array. Thid function takes a single argument, the value you want to fill the array with and applies it across the entire array.

This function is particularly useful for initializing or resetting all elements of the array to the same value.

Syntax

Following is the syntax for std::array::fill() function.

void fill (const value_type& val);

Parameters

  • val − It indicates the value to fill the array with.

Return Value

This function does not return anything.

Exceptions

None

Time complexity

Linear i.e. O(n)

Example 1

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

#include 
#include 
using namespace std;
int main(void) {
   int i;
   array < int, 5 > arr;
   for (i = 0; i < 5; ++i)
      arr[i] = i + 1;
   cout << "Original array\n";
   for (i = 0; i < 5; ++i)
      cout << arr[i] << " ";
   cout << endl;
   arr.fill(10);
   cout << "Modified array\n";
   for (i = 0; i < 5; ++i)
      cout << arr[i] << " ";
   cout << endl;
   return 0;
}

Output

Output of the above code is as follows −

Original array
1 2 3 4 5 
Modified array
10 10 10 10 10 

Example 2

Consider the following example, where we are going to use the fill() on the character array.

#include 
#include 
using namespace std;
int main() {
   array < char, 4 > MyArray {'p','r','a','s'};
   cout << "MyArray contains = ";
   for (int i = 0; i < MyArray.size(); i++)
      cout << MyArray[i] << " ";
   MyArray.fill('N');
   cout << "\nAfter fill() Myarray = ";
   for (int i = 0; i < MyArray.size(); i++)
      cout << MyArray[i] << " ";
   return 0;
}

Output

Following is the output of the above code −

MyArray contains = p r a s 
After fill() Myarray = N N N N 

Example 3

Let's look at the following example, where we are going to consider the string array and apply the fill() function.

#include 
#include 
using namespace std;
int main() {
   array < string, 2 > MyArray {"Tutorials","point"};
   cout << "MyArray contains = ";
   for (int i = 0; i < MyArray.size(); i++)
      cout << MyArray[i] << " ";
   MyArray.fill("LearningPlatform");
   cout << "\nAfter fill() Myarray = ";
   for (int i = 0; i < MyArray.size(); i++)
      cout << MyArray[i] << " ";
   return 0;
}

Output

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

MyArray contains = Tutorials point 
After fill() Myarray = LearningPlatform LearningPlatform 
array.htm
Advertisements