littlerunaway
littlerunaway

Reputation: 453

How to initialize a 2D array in a class?

I have a Matrix class that looks something like this:

template<int R, int C>
class Matrix{
public:
    double matrix[R][C];
    Matrix(double n = 0)...{}
    ...
};

Matrix<2,3> m;

How do I initialize the array when creating a new matrix with the n in the c'tor, without iterating over the whole array cell by cell?

I've read here some answers about something called memset, but I can't use it at the moment (it's a part of homework assignment).

Upvotes: 1

Views: 130

Answers (2)

PiotrNycz
PiotrNycz

Reputation: 24412

My advice is to use std algorithms wherever possible:

    std::for_each(std::begin(matrix), std::end(matrix), 
              [n](double* row) { std::fill_n(row, C, n); } );       

Full example:

template<int R, int C>
class Matrix{
public:
    double matrix[R][C];
    Matrix(double n = 0) {
         std::for_each(std::begin(matrix), std::end(matrix), 
                       [n](double* row) { std::fill_n(row, C, n); } );      
    }
};

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182769

Iterate over the whole array cell be cell using clear, simple, obvious code. If your compiler is sensible (and why use it if it's not) it will understand precisely what you are doing and substitute in the optimal initialization mechanism for your platform.

Upvotes: 0

Related Questions