0

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?

Eric L
  • 13
  • 2
  • 1
    *what is the best way* -- There is no "best way". There may be good ways, bad ways, or depends on use. By wording your question with "best way", the question now becomes opinion-based. – PaulMcKenzie Dec 26 '21 at 19:47
  • Thanks. Opinion based is ok as it might pertain to different use cases. – Eric L Dec 27 '21 at 20:07

1 Answers1

0

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;
  • Thanks. Another potential solution that I am thinking is to memset the row data of the array. – Eric L Dec 27 '21 at 20:10
  • `memset` is a concept of C. If you are trying to do it in C++, then use the functions in the STL like `std::fill` present in `` header, or you could try using `std::valarray` if you are applying many numerical computation on the elements. – alphapanda Dec 28 '21 at 07:18