您应该为Matrix(std::initializer_list</* here */> list);
. 然后要填充数组,您需要遍历传递的列表并填充数组。(见在线直播)
#include <initializer_list> // std::initializer_list
template<typename T, std::size_t R, std::size_t C>
class Matrix
{
T mArray2D[R][C]{};
public:
Matrix(const std::initializer_list<T[C]> list)
// ^^^^^ --> type of the row
{
auto iter{ list.begin() }; // returns pointer to T[C]
for (std::size_t row{}; row < R; ++row)
{
const auto& rowElements{ *iter };
for (std::size_t col{}; col < C; ++col)
{
mArray2D[row][col] = rowElements[col];
}
++iter;
}
}
};
现在,main()
您可以Matrix
使用初始化列表进行初始化,如下所示:
Matrix<int, 2, 2> mat{ {1,2}, {3,4} };
// or
// Matrix<int, 2, 2> mat = { {1,2}, {3,4} };
如果您可以使用std::array
,您可以执行以下操作。(见在线直播)
#include <iostream>
#include <array> // std::array
#include <initializer_list> // std::initializer_list
template<typename T, std::size_t R, std::size_t C>
class Matrix
{
using RowType = std::array<T, C>;
T mArray2D[R][C]{};
public:
Matrix(const std::initializer_list<RowType> list)
{
auto iter{ list.begin() };
for (std::size_t row{}; row < R; ++row)
{
const RowType& rowElements{ *iter };
for (std::size_t col{}; col < C; ++col)
{
mArray2D[row][col] = rowElements[col];
}
++iter;
}
}
};
如果类中的多维数组可以是std::array
of std::array
typeT
,您也可以使用std::copy
。(见在线直播)
#include <iostream>
#include <array> // std::array
#include <initializer_list> // std::initializer_list
#include <algorithm> // std::copy
template<typename T, std::size_t R, std::size_t C>
class Matrix
{
using RowType = std::array<T, C>;
using Array2D = std::array<RowType, R>;
Array2D mArray{ RowType{} }; // initialize the matrix
public:
Matrix(const std::initializer_list<RowType> list)
{
std::copy(list.begin(), list.end(), mArray.begin());
}
};