Is there is any function similar to memset() to initialize all elements of a two-dimensional array to a certain value? memset can only be used to initialize the values to 0 and -1.
The recommended approach to initialize an array with any value is using the Arrays. fill() method. For a 2D array, Arrays. fill() can be called for each array using a for-loop.
To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.
For a 2-Dimensional integer array, initialization can be done by putting values in curly braces "{" and "}". This list is called the value-list, a comma separated list of values of array elements. The data-type of these values should be same as data-type of the array (base type).
In C++ there are a function ( memset () ) which initialize the values of a 1D array and any multidimensional-array. but in java there are a function fill which initialize the 1D array but can't initialize the multidimensional-array . Show activity on this post.
Any 2-dimensional array can be declared as follows: data_type: Since Java is a statically-typed language (i.e. it expects its variables to be declared before they can be assigned values).
Multi-Dimensional Arrays comprise of elements that are themselves arrays. The simplest form of such arrays is a 2D array or Two-Dimensional Arrays. If an array has N rows and M columns then it will have NxM elements. 2-D Array Declaration is done as type array-name [rows] [columns].
You can use std::fill:
for(auto &arr : two_dim)
std::fill(std::begin(arr), std::end(arr), value);
This will work for many arrays and containers, like std::vector, std::array, and C arrays.
Also note that you can use memset to initialize all elements of an array to values other than -1 and 0. It's just that all the bytes in each element will have the same value, like 0x12121212.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With