Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero a 2d array in C++. Do I need 2 for loops?

Tags:

c++

arrays

How can I zero a 2D array in C++? Do I need two for loops just for that?

Coming from other higher languages, I wonder why C++ doesn't initialize arrays to meaningful/sensible defaults? Do I always need to declare an array then "zero" it out right afterwards?

like image 670
Jiew Meng Avatar asked Nov 17 '12 03:11

Jiew Meng


People also ask

How many for loops does a 2 dimensional array requires?

You can loop over a two-dimensional array in Java by using two for loops, also known as nested loop. Similarly to loop an n-dimensional array you need n loops nested into each other.

Why do we use two for loops when processing two-dimensional arrays?

For a two-dimensional array, in order to reference every element, we must use two nested loops. This gives us a counter variable for every column and every row in the matrix.

Do 2D arrays start at 0?

Accessing 2D Array Elements In Java, when accessing the element from a 2D array using arr[first][second] , the first index can be thought of as the desired row, and the second index is used for the desired column. Just like 1D arrays, 2D arrays are indexed starting at 0 .


2 Answers

C++ language tries to follow the principle of "you don't pay for what you don't use". It doesn't initialize fundamental types to any default values because you might not want it to happen. In any case, the language provides you the opportunity to explicitly request such initialization.

At the moment of declaration you can use initializers and simply do this

int array[10][20] = {};

or, for a dynamically allocated array

int (*array)[20] = new int[10][20]();

and this will give a zero-initialized array. No loops necessary.

But if you want to zero-out an existing array, then you will indeed have to use something more elaborate. In case of integer types a good old memset will work. For pointer or floating-point types the situation is in general case more complicated. memset might work or it might not work, depending on the implementation-defined properties. In any case, the standard library can help you to reduce the number of explicit loops by providing such loop wrappers as std::fill.

like image 60
AnT Avatar answered Nov 12 '22 07:11

AnT


Depends how you create it.

Two-dimensional vector, yes, two for-loops (because integers are primitive types - classes will call the default ctor).

Two-dimensional array? No, you can memset or bzero at once as the memory is all contiguous, whether using malloc or new.

like image 29
djechlin Avatar answered Nov 12 '22 06:11

djechlin