1

我正在尝试为线性代数计算编写一个矩阵类。我几乎写完了我想要的。但是我在创建一个使用列表初始化来创建矩阵的构造函数时遇到了一些麻烦。这是我的班级数据成员:

template <typename T>
class Matx
{
private:
    // data members
    //rows and columns of matrix
    int rows, cols;
    //pointer to pointer to type T
    T** matrix;

这是我的初始化代码:

template <typename T>
Matx<T>::Matx(T* ptM[], int m, int n) : rows(m), cols(n)
{
    matrix = new T*[rows];
    for (int i = 0; i < rows; i++)
        matrix[i] = new T[cols];
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            matrix[i][j] = *(ptM[i] + j);
}

主要:

double mat[][5] = { {5,5,-1,7,54},{4,-9,20,12,-6},{9,-18,-3,1,21},{ 61,-8,-10,3,13 },{ 29,-28,-1,4,14 } };
double* pm[5];
for (int i=0;i<5;i++)
    pm[i]=mat[i];
Matx<double> yourMat = Matx<double>(pm, 5,5);

但我认为有更好的方法来做到这一点。我想要的是能够像数组一样初始化它。像这样的东西:

Matx<double> yourMat = { {5,5,-1,7,54},{4,-9,20,12,-6},{9,-18,-3,1,21},{ 61,-8,-10,3,13 },{ 29,-28,-1,4,14 } };

可能吗?

4

2 回答 2

1

这绝对是可能的,我已经为类似的类创建了使用初始化列表的构造函数。像这样的构造函数应该可以完成这项工作:

template <typename T>
Matx<T>::Matx(std::initializer_list<std::initializer_list<T>> listlist) {
    rows = (int)(listlist.begin())->size();
    cols = (int)listlist.size();
    
    matrix = new T*[rows];
    
    for (int i = 0; i < rows; i++) {
        matrix[i] = new T[cols];
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = ((listlist.begin()+i)->begin())[j];
        }
    }
}
于 2017-02-06T15:07:50.730 回答
1

对于有类似问题的任何人,此版本对其他答案进行了一些小的更正。试过这个,它适用于 gcc 7.3,ubuntu 16.04。

template <typename T>
Matx<T>::Matx(std::initializer_list<std::initializer_list<T>> listlist) {
    rows = (int)(listlist.begin())->size(); /* pointer correction here */
    cols = (int)listlist.size();

    matrix = new T*[rows];

    for (int i = 0; i < rows; i++) {
        matrix[i] = new T[cols];
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = ((listlist.begin()+i)->begin())[j]; /* again minor correction */
        }
    }
}
于 2018-11-24T20:20:42.703 回答