码迷,mamicode.com
首页 > 其他好文 > 详细

4.3.2 稀疏矩阵转置(2)快速转置

时间:2020-04-13 10:37:44      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:iostream   tran   ++   end   out   nbsp   std   quick   矩阵转置   

SparseMatrix.h

#pragma once
#include<iostream>
using namespace std;

class Tri {
public:
    int col;
    int row;
    int value;
};

class SparseMatrix {
public:
    int term;
    Tri* elements;
    int Srow;
    int Scol;

    SparseMatrix(int t = 2, int r = 10, int c = 10) {
        term = t;
        Srow = r;
        Scol = c;
        elements = new Tri[term];
    }

    void quickTranspose(SparseMatrix& B) {
        int* rowCount;
        int* rowBegin;
        rowCount = new int[Scol];
        rowBegin = new int[Scol];
        for (int i = 0; i < Scol; i++) {
            rowCount[i] = 0;
        }
        for (int i = 0; i < term; i++) {
            rowCount[elements[i].col]++;
        }
        
        for (int i = 0; i < Scol; i++) {
            rowBegin[i] = 0;
        }
        
        for (int i = 1; i < Scol; i++) {
            rowBegin[i] = rowBegin[i - 1] + rowCount[i - 1];
        }
        cout << "RowBegin:" << endl;
        for (int i = 1; i < Scol; i++) {
            cout << i << ":" << rowBegin[i] << "  ";
        }
        cout << endl;
        //完成辅助数组

        int index_B = 0;
        for (int i = 0; i < term; i++) {
            index_B = rowBegin[elements[i].col];
            B.elements[index_B].col = elements[i].row;
            B.elements[index_B].row = elements[i].col;
            B.elements[index_B].value = elements[i].value;
            rowBegin[elements[i].col]++;
        }
    }

    void show() {
        for (int i = 0; i < term; i++) {
            cout << elements[i].row << "," << elements[i].col << "," << elements[i].value << endl;
        }
    }

};

main.cpp

#include"SparseMatrix.h"

int main() {
    SparseMatrix A, B;
    A.elements[0].col = 9;
    A.elements[0].row = 0;
    A.elements[0].value = 8;
    A.elements[1].col = 0;
    A.elements[1].row = 6;
    A.elements[1].value = 6;
    A.show();
    cout << "----------------------" << endl;
    A.quickTranspose(B);
    B.show();
    return 0;
}

 

4.3.2 稀疏矩阵转置(2)快速转置

标签:iostream   tran   ++   end   out   nbsp   std   quick   矩阵转置   

原文地址:https://www.cnblogs.com/SlowIsFast/p/12689709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!