Search code examples
c++listmatrixinitializing

list initialization for a matrix class


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?


Solution

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