c++ 稀疏矩阵变换

问题描述 投票:0回答:0

我需要实现一个获取矩阵的程序,以稀疏矩阵方式存储它,并输出转置矩阵。

#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;
}

输入

  • 第一行根据空格给出矩阵的行数R和列数C。 - 然后给每行 R 行一个基于空格的 C 整数。

输出

  • 从第二行开始使用稀疏矩阵输出转置矩阵

输入示例

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

我像代码一样做了它,但它没有按照我想要的方式工作,我不知道如何修复它。老师们帮帮我。 它没有按照我想要的方式打印出来。

c++ sparse-matrix transpose
© www.soinside.com 2019 - 2024. All rights reserved.