MST

星途 面试题库

面试题:C++类普通成员函数的功能设计之复杂逻辑

有一个C++类 `Matrix` 表示矩阵,包含成员变量 `rows`(行数)、`cols`(列数)以及一个二维 `vector<int>` 存储矩阵元素。设计一个普通成员函数 `transpose`,它的功能是对矩阵进行转置(即把矩阵的行和列互换),并返回转置后的新 `Matrix` 对象。同时要处理好内存管理问题,确保原矩阵和新矩阵的数据完整性和正确性。
35.6万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

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

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

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

    Matrix transpose() {
        Matrix transposed(cols, rows);
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                transposed.data[j][i] = data[i][j];
            }
        }
        return transposed;
    }
};