Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a 2D array with zero in the constructor C++

Tags:

c++

arrays

What is the best way to initialize a large 2D array with 0 in the constructor? I would like to do this without having to loop through my array, if possible.

like image 935
Kalmar Avatar asked Jun 01 '26 18:06

Kalmar


2 Answers

Alternatively, use a std::vector instead of an array.

std::vector<std::vector<int>> vec2d(100, std::vector<int>(50, 0));

The resulting two-dimensional vector will contain 100 vectors, each containing 50 zeros.

like image 158
A.B. Avatar answered Jun 03 '26 07:06

A.B.


use memset. For example:

int a[10][10]; 
memset(a, 0, sizeof(int)*10*10);
like image 20
Matt Avatar answered Jun 03 '26 07:06

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!