题目描述
设计一个矩阵类模板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;
}