Clear an Array in C++

In C++, there is no direct function to empty an array, but we can achieve this by using the std::fill() method from the <algorithm> library to set each element to its initial state.

Syntax of std::fill()

std::fill (arr, arr+n, defaultValue);

Here,

  • arr: Pointer to the first element of the array.
  • arr + n: Pointer to the hypothetical element after the last element of the array.
  • defaultValue: value to be set.

C++ Program to Empty an Array

The below program demonstrates how we can empty an array in C++ using the fill method.

C++




// C++ Program to illustrate how to empty an array                           
#include <algorithm>
#include <iostream>
using namespace std;
  
int main()
{
    // Initialize an array
    int arr[] = { 10, 20, 30, 40, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << "Original array: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
  
    // Empty the array by setting each element to 0 using
    // fill
    fill(arr, arr + n, 0);
  
    cout << "Array after emptying: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Original array: 10 20 30 40 50 
Array after emptying: 0 0 0 0 0 

Time Complexity: O(N), where N is the size of the array.
Auxiliary Space: O(1)

Note: We can also use memset() function to empty an array in C++.



How to Empty an Array in C++?

In C++, arrays are fixed-size containers that store elements of the same data type. Empty an array means removing all elements from it. In this article, we will see how to empty an array in C++.

Example:

Input:
myArray = { 1, 8, 2, 9, 1, 5, 6 }

Output:
myArray = { 0, 0, 0, 0, 0, 0, 0 }

Similar Reads

Clear an Array in C++

In C++, there is no direct function to empty an array, but we can achieve this by using the std::fill() method from the  library to set each element to its initial state....

Contact Us