温馨提示×

如何实现C++中的矩阵类

c++
小樊
84
2024-08-29 22:23:36
栏目: 编程语言

在 C++ 中,要实现一个矩阵类,你需要定义一个类,该类包含矩阵的数据(通常是一个二维向量)和相关的操作(如加法、乘法等)

#include<iostream>
#include<vector>

class Matrix {
public:
    // 构造函数
    Matrix(int rows, int cols) : _rows(rows), _cols(cols), _data(rows, std::vector<double>(cols, 0.0)) {}

    // 获取行数
    int getRows() const {
        return _rows;
    }

    // 获取列数
    int getCols() const {
        return _cols;
    }

    // 获取矩阵元素
    double getElement(int row, int col) const {
        return _data[row][col];
    }

    // 设置矩阵元素
    void setElement(int row, int col, double value) {
        _data[row][col] = value;
    }

    // 矩阵加法
    Matrix operator+(const Matrix& other) const {
        if (_rows != other._rows || _cols != other._cols) {
            throw std::invalid_argument("Matrix dimensions do not match for addition.");
        }

        Matrix result(_rows, _cols);
        for (int i = 0; i < _rows; ++i) {
            for (int j = 0; j < _cols; ++j) {
                result._data[i][j] = _data[i][j] + other._data[i][j];
            }
        }
        return result;
    }

    // 矩阵乘法
    Matrix operator*(const Matrix& other) const {
        if (_cols != other._rows) {
            throw std::invalid_argument("Matrix dimensions do not match for multiplication.");
        }

        Matrix result(_rows, other._cols);
        for (int i = 0; i < _rows; ++i) {
            for (int j = 0; j< other._cols; ++j) {
                for (int k = 0; k < _cols; ++k) {
                    result._data[i][j] += _data[i][k] * other._data[k][j];
                }
            }
        }
        return result;
    }

private:
    int _rows;
    int _cols;
    std::vector<std::vector<double>> _data;
};

int main() {
    // 创建两个矩阵并执行加法和乘法操作
    Matrix A(2, 2);
    A.setElement(0, 0, 1);
    A.setElement(0, 1, 2);
    A.setElement(1, 0, 3);
    A.setElement(1, 1, 4);

    Matrix B(2, 2);
    B.setElement(0, 0, 5);
    B.setElement(0, 1, 6);
    B.setElement(1, 0, 7);
    B.setElement(1, 1, 8);

    Matrix C = A + B;
    Matrix D = A * B;

    // 输出结果
    std::cout << "A + B = "<< std::endl;
    for (int i = 0; i < C.getRows(); ++i) {
        for (int j = 0; j < C.getCols(); ++j) {
            std::cout << C.getElement(i, j) << " ";
        }
        std::cout<< std::endl;
    }

    std::cout << "A * B = "<< std::endl;
    for (int i = 0; i < D.getRows(); ++i) {
        for (int j = 0; j < D.getCols(); ++j) {
            std::cout << D.getElement(i, j) << " ";
        }
        std::cout<< std::endl;
    }

    return 0;
}

这个示例展示了如何创建一个简单的矩阵类,包括构造函数、获取行数/列数、获取/设置矩阵元素以及矩阵加法和乘法操作。你可以根据需要扩展此类,添加更多功能。

0