Funky
Funky

Reputation: 101

How to clear out element inside an array?

I want to clear out all the element inside my array but I don't know how to automatically clear it out. is there a function for it? Like the clear() for lists??

int array[5] = {2,5,4,8,6};

then I want to clear out everything and add a new set of values

Upvotes: 1

Views: 125

Answers (2)

Yousaf
Yousaf

Reputation: 29282

Your question isn't valid because you can't clear out an array. An array has a fixed size and there always will be some value in it.

If you want to re-use an array, just overwrite the existing values.

Perhaps consider using std::vector. Using clear() function, you can clear all the values from the std::vector.

Learn about std::vector Here

Upvotes: 5

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

To clear an array means to set all values to T() that for arrays of fundamental arithmetic types is equivalent to set all elements to zeroes.

You can do it in several ways. The first one is to use standard C function std::memset declared in header <cstring>. For example

#include <iostream>
#include <cstring>

int main() 
{
    int array[] = { 2, 5, 4, 8, 6 };
    const size_t N = sizeof( array ) / sizeof( *array );

    for ( int x : array ) std::cout << x << ' ';
    std::cout << std::endl;

    std::memset( array, 0, N * sizeof( int ) );

    for ( int x : array ) std::cout << x << ' ';
    std::cout << std::endl;

    return 0;
}

Another way is to use standard algorithm std::fill declared in header <algorithm>. For example

#include <iostream>
#include <algorithm>

int main() 
{
    int array[] = { 2, 5, 4, 8, 6 };
    const size_t N = sizeof( array ) / sizeof( *array );

    for ( int x : array ) std::cout << x << ' ';
    std::cout << std::endl;

    std::fill( array, array + N, 0 );

    for ( int x : array ) std::cout << x << ' ';
    std::cout << std::endl;

    return 0;
}

In the both cases the program output is

2 5 4 8 6 
0 0 0 0 0 

If you need a variable length array then use standard container std::vector<int>.

For example

#include <iostream>
#include <iomanip>
#include <vector>

int main() 
{
    std::vector<int> array = { 2, 5, 4, 8, 6 };

    for ( int x : array ) std::cout << x << ' ';
    std::cout << std::endl;

    array.clear();

    std::cout << "array is empty - " << std::boolalpha << array.empty() << std::endl;

    return 0;
}

The program output is

2 5 4 8 6 
array is empty - true

Instead of array.clear(); there could be also used array.resize( 0 ); in the program.

Upvotes: 0

Related Questions