Eric L
Eric L

Reputation: 13

how to initialize muti-dimension C++ std arrays including zero initialization?

I have a two dimensional std array such as, array<array<int, 9>, 9> tbl;

How to initialize it with the same value such as -1? If I just want it to be zero-initialized, what is the best way to it?

Upvotes: 0

Views: 494

Answers (1)

alphapanda
alphapanda

Reputation: 1

As @PaulMcKenzie has stated, there isn't a single best way to do something.

For zero initializing the entire array, you can probably use aggregate initialization method.

std::array<std::array<int, N>, N> arr{0};

This method only works for zero-initialization of the array.

But if you want to initialize the array with a custom number throughout, you would need to iterate through all the elements and assign them manually.

std::array<std::array<int, N>, N> arr;

for(auto& row : arr)
  for(auto& i : row)
    i = -1;

Upvotes: 0

Related Questions