KrisjanisP's blog

By KrisjanisP, history, 3 years ago, In English

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.

  • Vote: I like it
  • +27
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it
Matrix operator *(const Matrix& other) const

and

for (const auto& x: C)
        for(int y: x)

And I not like inheritance all constructors from vector<vector<int>> — adds possibility to create like Matrix A = { { 1, 2, 3 }, { 1 } }