简体   繁体   English

如何在类中初始化2D数组?

[英]How to initialize a 2D array in a class?

I have a Matrix class that looks something like this: 我有一个看起来像这样的Matrix类:

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? 在使用c'tor中的n创建新矩阵时,如何在不逐个单元迭代整个数组的情况下如何初始化数组?

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). 我在这里阅读了一些有关memset答案,但目前无法使用(这是家庭作业的一部分)。

My advice is to use std algorithms wherever possible: 我的建议是尽可能使用std算法:

    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. 如果您的编译器明智(以及为什么不使用它),它将准确地了解您在做什么,并替代您平台的最佳初始化机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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