This post will discuss how to initialize a matrix in the C++ programming language.

A matrix, also known as a two-dimensional array, is basically an array of arrays. This post provides an overview of some of the available alternatives to initialize a matrix in C++:

1. Using Initializer list

We can initialize a fixed-length matrix with a value of 0 if we provide an empty initializer list or specify 0 inside the initializer list.

Download  Run Code

2. Using std::fill function

To initialize a fixed-length or variable-length matrix by any value in C++, the recommended solution is to apply the standard algorithm std::fill from the algorithm header.

Download  Run Code

 
This works since two-dimensional arrays are interpreted as a one-dimensional array in C++, and they can be entirely iterated through by a base-element pointer. So in the above expression, *mat is converted to a pointer to the first element of the matrix mat[0][0].

*mat is equivalent to any of the following expressions:

&mat[0][0] = &(*(mat[0] + 0)) = mat[0] + 0 = mat[0] = *(mat + 0) = *(mat)

3. Using range-based for-loop

Another simple and elegant way to initialize a matrix is using a range-based for-loop (since C++11).

Download  Run Code

4. Using std::for_each function

This can also be done using the standard algorithm std::for_each, as shown below:

Download  Run Code

 
Note that the global and static matrices are initialized with their default values when no initializer is specified. For instance, a global integer matrix will be zero-initialized by default.

That’s all about initializing a matrix in C++.

 
Also See:

Initialize multidimensional arrays in C