Operator Overloading

  • + 0 comments

    Hope this helps for easy solution and better understanding:

    class Matrix{
        public: 
            vector<vector<int>> a;
            
            Matrix operator +(const Matrix& b){
                int n = a.size();
                int m = a[0].size();
                Matrix result;
                result.a.resize(n, vector<int>(m, 0)); // 2D vector mxn with entries=0
                
                for(int i=0; i<n; i++){
                    for (int j=0; j<m; j++){
                        result.a[i][j] = a[i][j] + b.a[i][j];
                    }
                }
                return result;
            }     
    };