Matrix implementation allowing brace-enclosed initializer list C++

Правка en1, от 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;
    }
};
Теги c++11, matrix, implementation

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en4 Английский KrisjanisP 2022-06-18 12:10:42 0 (published)
en3 Английский KrisjanisP 2022-06-18 12:08:23 3
en2 Английский KrisjanisP 2022-06-18 11:52:55 376
en1 Английский KrisjanisP 2022-06-18 11:47:18 1313 Initial revision (saved to drafts)