Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set an array to zero with c++11

Tags:

c++

arrays

c++11

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.

like image 281
CodingCat Avatar asked Dec 15 '17 14:12

CodingCat


2 Answers

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 = {};
like image 80
François Andrieux Avatar answered Nov 10 '22 17:11

François Andrieux


You might use std::fill:

std::fill(std::begin(array), std::end(array), 0);
like image 31
Jarod42 Avatar answered Nov 10 '22 19:11

Jarod42