溫馨提示×

如何將C++矩陣類與其他數據結構結合使用

c++
小樊
82
2024-08-29 22:40:16
欄目: 編程語言

要將C++矩陣類與其他數據結構結合使用,首先需要創(chuàng)建一個矩陣類,定義一些基本操作(如初始化、訪問元素、矩陣運算等)

  1. 首先,創(chuàng)建一個矩陣類:
#include<iostream>
#include<vector>

class Matrix {
public:
    // 構造函數
    Matrix(int rows, int cols) : rows_(rows), cols_(cols), data_(rows * cols) {}

    // 獲取矩陣的行數
    int rows() const { return rows_; }

    // 獲取矩陣的列數
    int cols() const { return cols_; }

    // 訪問矩陣中的元素
    double& operator()(int row, int col) {
        return data_[row * cols_ + col];
    }

    // 訪問矩陣中的元素(常量版本)
    double operator()(int row, int col) const {
        return data_[row * cols_ + col];
    }

private:
    int rows_;
    int cols_;
    std::vector<double> data_;
};
  1. 然后,可以在主程序中使用這個矩陣類,并將其與其他數據結構(如向量、鏈表等)結合使用。例如,可以計算兩個矩陣的乘積:
Matrix multiply_matrices(const Matrix& A, const Matrix& B) {
    if (A.cols() != B.rows()) {
        throw std::invalid_argument("矩陣尺寸不匹配,無法相乘");
    }

    Matrix result(A.rows(), B.cols());
    for (int i = 0; i < A.rows(); ++i) {
        for (int j = 0; j < B.cols(); ++j) {
            for (int k = 0; k < A.cols(); ++k) {
                result(i, j) += A(i, k) * B(k, j);
            }
        }
    }
    return result;
}

int main() {
    Matrix A(2, 3);
    Matrix B(3, 2);

    // 初始化矩陣 A 和 B 的元素
    for (int i = 0; i < A.rows(); ++i) {
        for (int j = 0; j < A.cols(); ++j) {
            A(i, j) = i * j;
        }
    }

    for (int i = 0; i < B.rows(); ++i) {
        for (int j = 0; j < B.cols(); ++j) {
            B(i, j) = i + j;
        }
    }

    // 計算矩陣乘積
    Matrix C = multiply_matrices(A, B);

    // 輸出結果
    for (int i = 0; i < C.rows(); ++i) {
        for (int j = 0; j < C.cols(); ++j) {
            std::cout << C(i, j) << " ";
        }
        std::cout<< std::endl;
    }

    return 0;
}

這個示例展示了如何創(chuàng)建一個簡單的矩陣類,并將其與其他數據結構(如向量)結合使用。你可以根據需要擴展這個矩陣類,添加更多功能和操作。

0