I simply want to set a complete array back to 0. Something like a "reset" method.
I know that I can use something like this to initalize an array to zero:
int array[100] = {0}; //possible since c++11
but I am not sure to reset it. Something like array[100] = {0};
only sets the 100-element to 0. I know I can do it with a for loop, but there has to be a better way.
I am not allowed to use memset cause of the coding guideline.
For a C style array such as int array[100]
you can use std::fill
as long as array
is an array. A pointer to the array will not work.
std::fill(std::begin(array), std::end(array), 0);
If you are using a pointer to the first element, you must supply the size of your array yourself.
std::fill(array, array + size, 0);
In C++, it's recommended to use std::array
instead of C style arrays. For example, you could use std::array<int, 100> foo;
instead of int foo[100];
std::array
always knows its size, doesn't implicitly decay to a pointer and has value semantics. By using std::array
you can simply reset the array with :
foo.fill(0);
or
foo = {};
You might use std::fill
:
std::fill(std::begin(array), std::end(array), 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