【问题标题】:Initialising a two dimensional array within a class via the constructor通过构造函数在类中初始化二维数组
【发布时间】:2017-05-30 11:35:43
【问题描述】:

我有一个矩阵类,我希望能够用方括号列表初始化二维数据数组的值。我发现我可以通过在调用构造函数之前声明一个二维数组,然后将其作为构造函数参数传递来实现这一点。但是,我更希望能够将括号内的列表直接作为参数传递。

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

有没有办法做到这一点?我尝试使用嵌套的 std::arrays 无济于事(可能是因为它们的行为方式与 c 样式数组相同)。是否有可能通过初始化列表来实现这一点? (我尝试过使用 init-lists,但我不确定它们是否不合适,或者它们的行为是否与我期望的不同。)

我正在使用 gcc 和 c++14。

【问题讨论】:

    标签: c++ arrays constructor initialization c++14


    【解决方案1】:

    添加如下构造函数:

    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

    【讨论】:

    • 您能解释一下为什么我们必须使用这些额外的大括号吗?
    • @AndreasH。它们用于std::array 对象本身。
    • std::array 的用法非常简洁!
    • 谢谢!我以为我以前试过这个,但一定错过了一些东西。感谢您还解释了 std::initializer_list 的用法
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2015-07-13
    • 2018-07-22
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    相关资源
    最近更新 更多