【id:342】【16分】E. 矩阵类模板(类模板)

题目描述

设计一个矩阵类模板Matrix,支持任意数据类型的数据。

要求至少包含2个成员函数:矩阵转置函数transport、以及打印输出函数print

编写main函数进行测试,调用类的成员函数完成转置和输出。

输入

第一行先输入t,表示有t个测试用例

从第二行开始输入每个测试用例的数据。

首先输入数据类型,I表示int,D表示double,C表示char,接着输入两个参数m和n,分别表示矩阵的行和列

接下来输入矩阵的元素,一共m行,每行n个数据

输出

输入

2
I 2 3
1 2 3
4 5 6
C 3 3
a b c
d e f
g h i 

输出

1 4
2 5
3 6
a d g
b e h
c f i 

#include <iostream>

using namespace std;

template<typename T>
class Matrix {
private:
    int m, n; 
    T** mat;

public:
    Matrix(int rows, int cols) : m(rows), n(cols) {
        mat = new T * [m];
        for (int i = 0; i < m; ++i) {
            mat[i] = new T[n];
        }
    }

    ~Matrix() {
        for (int i = 0; i < m; ++i) {
            delete[] mat[i];
        }
        delete[] mat;
    }

    void transpose() {
        T** transposed = new T * [n];
        for (int i = 0; i < n; ++i) {
            transposed[i] = new T[m];
        }

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                transposed[j][i] = mat[i][j];
            }
        }


        for (int i = 0; i < m; ++i) {
            delete[] mat[i];
        }
        delete[] mat;

     
        mat = transposed;
        swap(m, n); 
    }

    void print() const {
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                cout << mat[i][j];
                if (j < n - 1) cout << " ";
            }
            cout << endl;
        }
    }

    void readMatrix() {
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                cin >> mat[i][j];
            }
        }
    }
};

int main() {
    int t;
    cin >> t;

    while (t--) {
        char type;
        int m, n;
        cin >> type >> m >> n;

        if (type == 'I') {
            Matrix<int> mat(m, n);
            mat.readMatrix();
            mat.transpose();
            mat.print();
        }
        else if (type == 'D') {
            Matrix<double> mat(m, n);
            mat.readMatrix();
            mat.transpose();
            mat.print();
        }
        else if (type == 'C') {
            Matrix<char> mat(m, n);
            mat.readMatrix();
            mat.transpose();
            mat.print();
        }

  
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值