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)?
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.
std::fill_n(array, elementCount, 0);
Assuming array
is a normal array (e.g. int[]
)
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With