list initialization for a matrix class

那年仲夏 提交于 2019-12-12 03:57:57

问题


I am trying to write a matrix class for linear algebra calculations. I have almost finished writing what I wanted. but I have a little trouble in creating a constructor that uses list initialization to create a matrix. this is my class data members:

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

and this is my code for initialization:

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);
}

in main:

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);

but I think there is a better way to do it. what I want is to be able to initialize it like arrays. something like this:

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 } };

Is it possible?


回答1:


It is definitely possible, I have made constructors that use initializer lists for similar classes. A constructor like this should do the job:

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)[j];
        }
    }
}



回答2:


For anyone with similar issue, this version has some minor corrections to the other answer. Tried this and it works in 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 */
        }
    }
}


来源:https://stackoverflow.com/questions/42068882/list-initialization-for-a-matrix-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!