Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize all elements of a two-dimensional array to a particular value?

Tags:

c++

c++14

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.

like image 638
You Know Who Avatar asked Apr 30 '20 15:04

You Know Who


People also ask

How do you initialize a 2D array with values?

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.

How do you initialize a 2D array?

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.

How to initialize a 2 dimensional array in C++?

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).

How to initialize a multidimensional array in Java?

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.

How to declare a 2-dimensional array in Java?

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).

What are multi-dimensional arrays?

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].


1 Answers

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.

like image 114
S.S. Anne Avatar answered Oct 12 '22 14:10

S.S. Anne