通过构造函数在类中初始化二维数组
Initialising a two dimensional array within a class via the constructor
我有一个矩阵类,我希望能够在其中初始化带有包围列表的两个维数据数组的值。我发现我可以通过在调用构造函数之前声明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
。
相关文章:
- 在C++中初始化第一维大小未知的二维数组
- 使用lambdas初始化多维数组
- 如何在编译时初始化静态二维数组
- 如何在 c++ 中初始化构造函数中的二维数组
- 二维数组未正确初始化
- 从二维数组中的char*初始化c++字符串时,读取大小为1的无效值
- 二维数组初始化
- 使用 char 初始化多维数组
- 初始化和删除二维数组
- 初始化多维数组中的所有位置
- 初始化多维数组的元素
- 二维数组的初始化数组
- 二维数组初始化值
- 初始化具有特定值的可变二维数组
- 如何在c++中初始化多维数组
- 动态初始化多维数组时出现重复变量错误
- 如何用null声明和初始化多维数组
- 用零初始化多维数组
- 如何在c++构造函数中初始化多维数组
- 如何在Qt/ c++中有效地重新初始化多维数组