稀疏矩陣三元組順序表

有這樣一種矩陣,大多數元素的值爲零,只有少部分爲非零元素。而這些非零元素在矩陣中的分佈又沒有明顯的規律,這種矩陣稱爲稀疏矩陣。本文才有順序組織來存儲稀疏矩陣,存取稀疏矩陣非零元素需要三個參數,行號、列號和數據值。

本文實現了稀疏矩陣的構造和轉置以及顯示。

thrinode.h

#ifndef THRINODE_H_
#define THRINODE_H_
const int MAXSIZE=50;
typedef int ElemType;
//定義三元組結構體
struct Thrinode
{
	int i;//非零元素的行號
	int j;//非零元素的列號
	ElemType v;//非零元素的數據值
};
//三元表類定義
class SqMatrix
{
private:
	int m;//矩陣的總行數
	int n;//矩陣的總列數
	int t;//非零元素的個數
	Thrinode data[MAXSIZE];//三元組表
public:
	SqMatrix();//構造函數
	void Create();//輸入建立一個矩陣
	SqMatrix TransmatOne();//轉置方法1
	SqMatrix Transmatone();//裝置方法1的另一種方式
	void showMatrix();//輸出顯示
};
#endif
thrinode.cpp

#include "stdafx.h"
#include "thrinode.h"
#include <iostream>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
SqMatrix::SqMatrix()//構造函數
{
	m=0; n=0; t=0;
	 //初始化一個空三元組表
	for(int p=0; p<t; p++)
	{
		data[p].i=0;
		data[p].j=0;
		data[p].v=0;
	}
}
void SqMatrix::Create()//輸入建立一個矩陣
{
	cout<<"請輸入您要創建的稀疏矩陣維數:"<<endl;
	cout<<"總行數 m = ";cin>>m;
	cout<<"總列數 n = "; cin>>n;
	cout<<"非零元素總個數 t = ";cin>>t;
	cout<<"**********************************"<<endl;
	for(int p=0; p<t; p++)
	{
		cout<<"第"<<p+1<<"個元素爲:"<<endl;
		cout<<"行號:i = ";
		cin>>data[p].i;
		cout<<"列號:j = ";
		cin>>data[p].j;
		cout<<"元素值:v = ";
		cin>>data[p].v;
	}
	cout<<"矩陣創建完畢!"<<endl;
}

SqMatrix SqMatrix::TransmatOne()//轉置方法1
{
	SqMatrix b;
	cout<<"按矩陣的列序轉置開始"<<endl;
	b.m=n; b.n=m; b.t=t;
	if(t!=0)
	{
		int q=0;
		for(int col=1; col<=n; col++)
		{
			for(int p=0; p<t; p++)
			{
				if(data[p].j==col)
				{
					b.data[q].j=data[p].i;
					b.data[q].i=data[p].j;
					b.data[q].v=data[p].v;
					++q;

				}
			}
		}
		cout<<"轉置已經完成"<<endl;
		return b;
	}
}
SqMatrix SqMatrix::Transmatone()//裝置方法1的另一種方式
{
	SqMatrix b;
	b.m=m; b.n=n; b.t=t;
	if(t!=0)
	{//
		cout<<"按矩陣的行序轉置開始:"<<endl;
		for(int p=1; p<=m; p++)
		{
			for(int q=0; q<=t; q++)
			{
				if(p==data[q].i)
				{
					b.data[q].i=data[q].j;
					b.data[q].j=data[q].i;
					b.data[q].v=data[q].v;
				}
			}
		}
		cout<<"轉置變換結束。。。"<<endl;
	}
	return b;
}
void SqMatrix::showMatrix()//輸出顯示
{
	for(int i=1; i<=m; i++)
	{
		for(int j=1; j<=n; j++)
		{
		    bool isFound=false;
			int foundIndex=0;
			for(int p=0; p<t; p++)
			{

				if(data[p].i==i && data[p].j==j)
				{
					isFound=true;
					foundIndex=p;
					//cout<<std::setw(5)<<data[p].v;
				}	
			}
			if(isFound==true)
			{
				cout<<std::setw(5)<<data[foundIndex].v;
			}
			else
			{
				cout<<std::setw(5)<<0;
			}
		}
		cout<<endl;
	}
}
main.cpp

// main.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
#include <iostream>
#include "thrinode.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	SqMatrix Matrix;
	Matrix.Create();
	Matrix.showMatrix();
	SqMatrix TM=Matrix.TransmatOne();
	TM.showMatrix();
	SqMatrix TMD=Matrix.Transmatone();
	TMD.showMatrix();
	system("pause");
	return 0;
}
結果:



發佈了70 篇原創文章 · 獲贊 44 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章