Matrix implementation allowing brace-enclosed initializer list C++

Revision en1, by KrisjanisP, 2022-06-18 11:47:18

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 described in on stackexchange. In C++11, a form of 'constructor inheritance' has been introduced. 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;
    }
};
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)