稀疏矩阵的实现(三元组存储)C++

本文详细介绍了如何使用C++通过三元组来实现稀疏矩阵的压缩存储,旨在节省空间,提高效率。
摘要由CSDN通过智能技术生成

通过三元组存储稀疏矩阵,压缩存储空间

/*
稀疏矩阵的实现
*/
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//存储域
const int MAX_N = 100;
class elem_node
{
public:
	int elem_row;//元素行号
	int elem_col;//元素列号
	int elem_value;//元素值
};

class Node
{
public:
	int total_row;//总行数
	int total_col;//总列数
	int total_num;//非0元素总数
	elem_node data[MAX_N];//非0元素数组
};

class Matrix
{
public:
	Matrix(){}
	~Matrix(){}
	//构建稀疏矩阵三元组
	void CreateMat(string filename, int rows, int cols)
	{
		int i, j;
		int fdata;
		ifstream readFile;
		mat.total_num = 0;
		mat.total_col = cols;//总行数
		mat.total_row = rows;//总列数
		readFile.open(filename);
		//打开错误
		if (readFile.bad() || readFile.fail())
		{
			exit(0);
		}
		//文件正常打开
		if (readFile.is_open())
		{
			for (i = 0; i < rows; i++)
			{
				for (j = 0; j < cols; j++)
				{
					readFile >> fdata;
					if (readFile.good() && fdata != 0)
					{
						mat.data[mat.total_num].elem_row = i;//元素行号
						mat.data[mat.total_num].elem_col = j;//元素列号
						mat.data[mat.total_num].elem_value = fdata;//元素之
						mat.total_num++;//存储数组下标+1
					}
				}
			}
		}
		readFile.close();
	}
	//指定位置赋值,若不存在,则插入
	bool Value(int elem, int i, int j)
	{
		if (i >= mat.total_row || j >= mat.total_col)
		{
			return false;
		}
		else
		{
			int k = 0, k1;
			//搜索行号<3,5> <3,6> <3,7> <3,8> 查找<3,6>
			while (k<mat.total_num&&i>mat.data[k].elem_row)
			{
				k+&#
  • 5
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值