C++ std::array::fill

The std::array::fill function assigns the specified value to all elements of the array. It is a convenient way to initialize or reset all elements of the array with the same value in a single operation.


Syntax of std::array::fill

</>
Copy
void fill(const T& value);

Parameters

ParameterDescription
valueThe value to be assigned to all elements of the array.

Return Value

The std::array::fill function does not return any value. It modifies the elements of the array in place.

Exceptions

The std::array::fill function does not throw exceptions unless the assignment operator of the type T throws an exception.


Examples for std::array::fill

Example 1: Using std::array::fill to Initialize an Array

This example demonstrates how to use fill to initialize all elements of a std::array with the same value:

</>
Copy
#include <iostream>
#include <array>

int main() {
    std::array<int, 5> arr;

    arr.fill(10); // Fill the array with the value 10

    std::cout << "Array elements: ";
    for (const auto& elem : arr) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. An uninitialized std::array named arr is defined with a size of 5.
  2. The fill function is used to assign the value 10 to all elements of the array.
  3. A range-based for loop iterates through the array and prints the elements.

Output:

Array elements: 10 10 10 10 10

Example 2: Using std::array::fill to Reset Array Elements

This example demonstrates how to use fill to reset all elements of an array to a default value:

</>
Copy
#include <iostream>
#include <array>

int main() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5};

    std::cout << "Original array: ";
    for (const auto& elem : arr) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    arr.fill(0); // Reset all elements to 0

    std::cout << "Array after reset: ";
    for (const auto& elem : arr) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. A std::array named arr is initialized with the values {1, 2, 3, 4, 5}.
  2. The elements of the array are printed using a range-based for loop.
  3. The fill function is used to reset all elements to 0.
  4. The updated array is printed to confirm the change.

Output:

Original array: 1 2 3 4 5
Array after reset: 0 0 0 0 0