Matrix implementation allowing brace-enclosed initializer list in C++

Revision en3, by KrisjanisP, 2022-06-18 12:08:23

When solving a matrix exponention task I found myself wanting to overload the multiplication operator and to able to initialize a matrix like I would initialize a short vector with known values, i.e., vector<int> vec = {1,2,3};

Inheriting the struct from vector<vector<int>> seemed useful. Not only that would allow for easy initialization it would also provide access to [] operator and many other useful vector methods.

I discovered that the constructor is not inherited :(

There is however a workaround introduced in C++11 described on stackexchange.

The final struct looks something like this:

struct Matrix:vector<vector<int>>
{
    // "inherit" vector's constructor
    using vector::vector;
    
    Matrix operator *(Matrix other)
    {
        int rows = size();
        int cols = other[0].size();
        Matrix res(rows, vector<int>(cols));
        for(int i=0;i<rows;i++)
            for(int j=0;j<other.size();j++)
                for(int k=0;k<cols;k++)
                    res[i][k]+=at(i).at(j)*other[j][k];
        return res;
    }
};

Creating the struct this way allows for using it this way:

    Matrix A = {{19,7},{6, 20}};
    Matrix B = {{19,7},{6, 20}};
    Matrix C = A*B;
    for(auto x: C)
        for(int y: x)
            cout<<y<<" ";

The code outputs 403 273 234 442.

Tags c++11, matrix, implementation

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English KrisjanisP 2022-06-18 12:10:42 0 (published)
en3 English KrisjanisP 2022-06-18 12:08:23 3
en2 English KrisjanisP 2022-06-18 11:52:55 376
en1 English KrisjanisP 2022-06-18 11:47:18 1313 Initial revision (saved to drafts)