Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear a C++ array?

Tags:

How do I clear/empty a C++ array? Theres array::fill, but looks like its C++11 only? I am using VC++ 2010. How do I empty it (reset to all 0)?

like image 659
Jiew Meng Avatar asked Nov 09 '12 12:11

Jiew Meng


People also ask

Can you remove elements from an array in C?

In C programming, an array is derived data that stores primitive data type values like int, char, float, etc. To delete a specific element from an array, a user must define the position from which the array's element should be removed. The deletion of the element does not affect the size of an array.


2 Answers

std::fill_n(array, elementCount, 0);

Assuming array is a normal array (e.g. int[])

like image 89
Angew is no longer proud of SO Avatar answered Sep 23 '22 01:09

Angew is no longer proud of SO


Assuming a C-style array a of size N, with elements of a type implicitly convertible from 0, the following sets all the elements to values constructed from 0.

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

Note that this is not the same as "emptying" or "clearing".

Edit: Following james Kanze's suggestion, in C++11 you could use the more idiomatic alternative

std::fill( std::begin( a ), std::end( a ), 0 );

In the absence of C++11, you could roll out your own solution along these lines:

template <typename T, std::size_t N> T* end_(T(&arr)[N]) { return arr + N; }

template <typename T, std::size_t N> T* begin_(T(&arr)[N]) { return arr; }

std::fill( begin_( a ), end_( a ), 0 );
like image 44
juanchopanza Avatar answered Sep 25 '22 01:09

juanchopanza