#include <iostream>
using namespace std;
const int MAX = 100;
typedef struct{ //定义添加元素的属性
int row;
int col;
int item;
}Tripe;
class TripleMatrix {
private:
Tripe data[MAX];
int m, n, num;
public:
TripleMatrix(int, int); //有参构造
TripleMatrix(); //无参构造
~TripleMatrix(); //析构
bool setItem(Tripe); //元素赋值
int getIetm(int, int); //获取元素值
void printMatrix(); //按矩阵形式输出
void printTripe(); //按压缩形式输出
};
TripleMatrix::TripleMatrix(int m, int n) {
this->m = m;
this->n = n;
num = 0;
}
TripleMatrix::TripleMatrix() {
m = n = num = 0;
}
TripleMatrix::~TripleMatrix() {}
bool TripleMatrix::setItem(Tripe tripe) { //插入非零元
if (tripe.row > m || tripe.col > n) //超过最大行列数
return false;
if (num == MAX) //超过非零元素个数
return false;
if (tripe.item == 0) //插入元素值为0
return false;
int i = 0; //标记当前元素在非零元素中的排序
while (i < num) {
if (tripe.row > data[i].row) //当前行低于目标行
i++;
else if ((tripe.row == data[i].row) && (tripe.col > data[i].col)) //当前列低于目标列
i++;
else //到位
break;
}
if((tripe.row == data[i].row) && (tripe.col == data[i].col)) { //当前位置有非零元直接替换
data[i] = tripe;
return true;
}
else{ //当前位置为零,则向后移动
for(int j = num; j > i; j--)
data[j] = data[j-1];
data[i] = tripe;
num++;
return true;
}
}
int TripleMatrix::getIetm(int row, int col) {
int i;
if (row > m || col > n)
return 0;
else
for (i = 0; i < num; i++)
if (data[i].row == row && data[i].col == col)
return data[i].item;
}
void TripleMatrix::printMatrix() {
int temp = 0;
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if((data[temp].row == i) && (data[temp].col == j)) {
cout << data[temp].item << " ";
temp++;
}
else
cout << 0 << " ";
}
cout << endl;
}
cout << "m = " << m << " n = " << n << " num = " << temp << endl;
}
void TripleMatrix::printTripe() {
for(int i = 0; i < num; i++)
cout << data[i].item << endl;
}
稀疏矩阵的存取
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 稀疏矩阵 在矩阵中,若数值为0的元素数目远远多于非0元素的数目时,则称该矩阵为稀疏矩阵。与之相反,若非0元素数目占...
- 所使用的R包:DropletUtils 函数:write10xCounts
- 简介 稀疏矩阵是矩阵中的非零元素个数远远少于零元素个数。一般会通过稀疏因子来进行确定。假设在m×n的矩阵中,有t个...
- sparse scipy 从稀疏矩阵中选取某些指定列构成新的稀疏矩阵主要想法:1.getcol(i)获得指定行2....
- 参考资料:Sparse Matrices For Efficient Machine LearningIntrod...