MST

星途 面试题库

面试题:C++运算符重载的复杂场景

假设有一个 `Matrix` 类表示矩阵,它有一个二维数组作为成员变量存储矩阵元素。请实现 `Matrix` 类的乘法运算符 `*` 的重载,要考虑矩阵乘法的规则,即矩阵A(m×n)与矩阵B(n×p)相乘得到矩阵C(m×p),同时要处理维度不匹配的异常情况,并说明如何保证运算符重载的效率和正确性。
46.8万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <vector>
#include <stdexcept>

class Matrix {
private:
    std::vector<std::vector<int>> data;
    int rows;
    int cols;

public:
    Matrix(int r, int c) : rows(r), cols(c), data(r, std::vector<int>(c, 0)) {}

    int getRows() const {
        return rows;
    }

    int getCols() const {
        return cols;
    }

    int& operator()(int i, int j) {
        return data[i][j];
    }

    const int& operator()(int i, int j) const {
        return data[i][j];
    }

    Matrix operator*(const Matrix& other) const {
        if (cols != other.rows) {
            throw std::invalid_argument("矩阵维度不匹配,无法相乘");
        }

        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(i, j) += data[i][k] * other(k, j);
                }
            }
        }

        return result;
    }
};

int main() {
    try {
        Matrix A(2, 3);
        A(0, 0) = 1; A(0, 1) = 2; A(0, 2) = 3;
        A(1, 0) = 4; A(1, 1) = 5; A(1, 2) = 6;

        Matrix B(3, 2);
        B(0, 0) = 7; B(0, 1) = 8;
        B(1, 0) = 9; B(1, 1) = 10;
        B(2, 0) = 11; B(2, 1) = 12;

        Matrix C = A * B;

        for (int i = 0; i < C.getRows(); ++i) {
            for (int j = 0; j < C.getCols(); ++j) {
                std::cout << C(i, j) << " ";
            }
            std::cout << std::endl;
        }
    } catch (const std::invalid_argument& e) {
        std::cerr << "异常: " << e.what() << std::endl;
    }

    return 0;
}

效率和正确性保证

  1. 正确性
    • 在进行矩阵乘法之前,先检查两个矩阵的维度是否匹配。如果 A 矩阵的列数不等于 B 矩阵的行数,则抛出 std::invalid_argument 异常,以保证只有在满足矩阵乘法规则的情况下才进行运算。
    • 在进行乘法运算时,严格按照矩阵乘法的定义,通过三层循环遍历矩阵元素并进行乘法和累加操作,确保计算结果的正确性。
  2. 效率
    • 对于小型矩阵,上述实现已经是较为直接和高效的方式。因为矩阵乘法本身的时间复杂度为 $O(m \times n \times p)$,这里的实现直接遵循了这个复杂度。
    • 对于大型矩阵,可以考虑使用一些优化策略,例如分块矩阵乘法、并行计算(如使用OpenMP进行多线程并行计算矩阵乘法)等方式来提高运算效率。但在基本实现中,为了保持代码的简洁和清晰,未引入这些复杂的优化。