简体   繁体   中英

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

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); } );      
    }
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM