Set an array to zero with c++11

12,696

Solution 1

You might use std::fill:

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

Solution 2

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 = {};
Share:
12,696
CodingCat
Author by

CodingCat

Updated on June 16, 2022

Comments

  • CodingCat
    CodingCat almost 2 years

    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.

  • chris
    chris over 6 years
    If it's more clear to you, std::array also has arr.fill(0)
  • François Andrieux
    François Andrieux over 6 years
    @chris Thank you, I've appended my answer.
  • Phlucious
    Phlucious over 5 years
    How do you know the default value assigned by foo = {}?
  • François Andrieux
    François Andrieux over 5 years
    @Phlucious That's aggregate initialization. If the list is empty or shorter than the number of elements, the remaining elements are value initialized. For int type elements, that means initializing them to zero.
  • sɪʒɪhɪŋ βɪstɦa kxɐll
    sɪʒɪhɪŋ βɪstɦa kxɐll over 2 years
    If you want to create an std::array initialized to zero you can create the array as c++ std::array<int, 100> row({0}); because the object in its construction calls std::fill_n, that for C++20, I don't know for previous standards.