通过构造函数在类中初始化二维数组

Initialising a two dimensional array within a class via the constructor

本文关键字:初始化 二维数组 构造函数      更新时间:2023-10-16

我有一个矩阵类,我希望能够在其中初始化带有包围列表的两个维数据数组的值。我发现我可以通过在调用构造函数之前声明2D数组来实现这一目标,然后将其作为构造函数参数。但是,我宁愿能够直接通过括号列表作为参数。

template <class T, unsigned int N, unsigned int M>
class Matrix
{
    T data[N][M];
    Matrix(const T initMat[N][M])
    {
        for (unsigned int i=0; i<N; ++i)
        {
            for (unsigned int j=0; j<M; ++j)
            {
                data[i][j] = initMat[i][j];
            }
        }
    }
};


const double arr[2][2] = {{1.0,2.0},{3.0,4.0}};
Matrix<double, 2, 2> matA(arr);    // Valid

Matrix<double, 2, 2> matB({{1.0,2.0},{3.0,4.0}});    // Invalid

有没有办法实现这一目标?我尝试使用Nested STD ::阵列无济于事(大概是因为它们的作用与C风格数组相同(。可以通过初始列表实现这一目标吗?(我尝试使用启动名单,但我不确定它们是否不合适,或者是否不像我期望的那样行事。(

我正在使用GCC和C 14。

添加一个构造函数,例如:

Matrix(std::array<std::array<T, M>, N> const& initMat) { ... }

并添加另一套卷曲式(对于std::array对象(:

Matrix<double, 2, 2> matB({{{1.0,2.0},{3.0,4.0}}});

或使用std::initialize_list喜欢:

Matrix(std::initializer_list<std::initializer_list<T>>){}

然后您可以从上面的定义中删除括号(和一对卷发(:

Matrix<double, 2, 2> matB{{1.0,2.0},{3.0,4.0}};

缺点是初始化列表的大小不会执行。因此,我建议使用std::array

推荐第一个变体