我需要实现一个获取矩阵的程序,以稀疏矩阵方式存储它,并输出转置矩阵。
#include <iostream>
using namespace std;
const int MAX_TERMS = 101;
class MatrixTerm{
friend class SparseMatrix;
private:
int row, col, value;
};
class SparseMatrix{
public:
SparseMatrix(int r, int c, int t);
SparseMatrix Transpose();
void print();
private:
int Rows, Cols, Terms, Capacity;
MatrixTerm *smArray;
};
SparseMatrix::SparseMatrix(int r, int c, int t)
{
Rows = r;
Cols = c;
Terms = t;
Capacity = MAX_TERMS;
smArray = new MatrixTerm[Capacity];
for(int i = 0; i < Terms; i++){
int row, col, value;
cin >> row >> col >> value;
smArray[i].row = row;
smArray[i].col = col;
smArray[i].value = value;
}
}
SparseMatrix SparseMatrix::Transpose()
{
SparseMatrix b(Cols, Rows, Terms);
if(Terms > 0){
int currentB = 0;
for(int c = 0; c < Cols; c++){
for(int i = 0; i < Terms; i++){
if(smArray[i].col == c){
b.smArray[currentB].row = smArray[i].col;
b.smArray[currentB].col = smArray[i].row;
b.smArray[currentB++].value = smArray[i].value;
}
}
}
}
return b;
}
void SparseMatrix::print()
{
SparseMatrix t = Transpose();
for(int i = 0; i < t.Terms; i++){
cout << t.smArray[i].row << " " << t.smArray[i].col << " " << t.smArray[i].value << endl;
}
}
int main()
{
int rows, cols;
cin >> rows >> cols;
SparseMatrix A(rows, cols, 0);
A.print();
return 0;
}
输入
输出
输入示例
5 5
0 1 0 2 0
3 0 4 0 0
0 0 0 0
0 0 0 0
0 0 0 0
输出示例
1 2 3
2 1 1
3 2 4
4 1 2
我像代码一样做了它,但它没有按照我想要的方式工作,我不知道如何修复它。老师们帮帮我。 它没有按照我想要的方式打印出来。