数据结构之稀疏矩阵C++版

//只是简单的演示一下,这个实际运用视乎不怎么多,所以java版不再实现

/*
    希疏矩阵应用于对数据的压缩,仅仅保留不为0的数据
    稀疏矩阵的转置,可以由多种方式,下面演示的稍显简单,时间复杂度略高O(n^2)
*/



//先来一个矩阵
int a[][4] = {
    9,0,0,6,
    0,4,0,0,
    5,0,0,0,
    0,0,8,0,
};
//来个三元组
template <class T>
struct Three
{
    int _row, _col;//存放行列
    T value;//存放值
};

class Transform {
public:
    int count=0;
    Three<int> three[4];
    void init(){//将不为0的数组保存下来
        for (int i = 0;i < 4;i++) {
            for (int j = 0;j < 4;j++) {
                if (a[i][j] != 0){
                    three[count]._row = i;
                    three[count]._col = j;
                    three[count].value = a[i][j];
                    count++;
                }
            }
        }
    }
    void tF() {//转置矩阵
        for (int i = 0;i < count - 1;i++) {
            int col = three[i]._col;
            three[i]._col = three[i]._row;
            three[i]._row = col;
        }
    }
};
int main()
{

    Transform *form = new Transform();
    form->init();
    printf("row %d,col %d
", form->three[1]._row, form->three[1]._col);
    form->tF();
    printf("row %d,col %d", form->three[1]._row, form->three[1]._col);
    while (1);
    return 0;
}

 

原文地址:https://www.cnblogs.com/enjoyall/p/6013814.html