C++ 实现矩阵类(个人学习记录)

#include <iostream>
#include <vector>
#include <assert.h>

class Matrix{
private:
    int row;
    int col;
    std::vector<std::vector<int>> data;
public:
    Matrix() = default;

    Matrix(int row, int col): row(row), col(col), data(row , std::vector<int>(col, 0)){};

    Matrix(std::vector<std::vector<int>> elements){
        this->row = elements.size();
        this->col = elements[0].size();
        this->data = elements;
    };

    /**
     * 
    */

    // std::ostream& operator<<(std::ostream& os){
    //     os << this->row << " -- " << this->col << std::endl;
    //     return os;
    // };

    std::vector<int>& operator[](int index){
        return this->data[index];
    };

    Matrix operator*(Matrix& b){
        assert(this->col == b.row);
        Matrix c(this->row, this->col);
        for(int i = 0; i < this->row; i++){
            for(int j = 0; j < this->col; j++){
                for(int k = 0; k < this->col; k++){
                    c[i][j] += this->data[i][k] * b[k][j];
                }
            }
        }
        return c;
    };

    void show(){
        for(int i = 0; i < this->row; i++){
            std::cout << "[";
            for(int j = 0; j < this->col; j++){
                std::cout << this->data[i][j] << " ";
            }
            std::cout << "]" << std::endl;
        }
    }
};


// std::ostream& operator<<(std::ostream os, )

int main(){
    
    Matrix a({{1,0,0}, {0,1,0}, {0,0,1}});
    Matrix b({{1,2,3}, {1,1,1}, {0,0,1}});
    // std::cout << a;      // 类内部重载 << 时这个写法错误
    // a << std::cout;         // 类内部重载 << 时只能这么写,反常规
    Matrix c = a * b;
    c.show();
    // [1 2 3 ]
    // [1 1 1 ]
    // [0 0 1 ]
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值