1. 程式人生 > >利用稀疏矩陣的“三元組表”儲存結構,實現兩個矩陣的相加。

利用稀疏矩陣的“三元組表”儲存結構,實現兩個矩陣的相加。

#include<iostream>
#include<conio.h>
#include<iomanip>
using namespace std;
const int MAXSIZE = 50;
typedef int ElemType;
struct MAT
{
    int i;
    int j;
    ElemType v;
};
class SqMatrix
{
private:
    int m;
    int n;
    int t;
    MAT data[MAXSIZE];
public:
    SqMatrix();
    void create();
    SqMatrix operator +(SqMatrix B);
    void showMatrix();
};
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()
{
    int ii,jj,element;
    cout<<"\n       Input the Matrix number:"<<endl;
    cout<<"\n       Total column number:";cin>>m;cout<<"\n  Total Line number:";cin>>n;
    cout<<"\n   The number of not zero:t= ";cin>>t;
    cout<<"\n   Input the "<<m<<" columns"<<n<<" lines of Matrix"<<endl;
    cout<<"----------------"<<endl;
    for(int p=0;p<t;p++)
    {
        cout<<"\n   column:i= ";cin>>ii;data[p].i=ii;
        cout<<"\n   lines:j=  ";cin>>jj;data[p].j=jj;
        cout<<"\n   The number of not zero:v= ";cin>>element;data[p].v=element;
    }
    cout<<"Ok."<<endl;
}
void SqMatrix::showMatrix()
{
    for(int i=1;i<=m;i++)
    {
        cout<<endl;
        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;
                }
                if (isFound==true)cout<<setw(5)<<data[foundIndex].v;
                else cout<<setw(5)<<"0";            }
        }
    }
}
SqMatrix SqMatrix::operator+(SqMatrix B)
{
    SqMatrix C;
    int p,q,k=0;
    p=q=0;
    C.m=m;
    C.n=n;
    while(p<t&&q<B.t)
    {
        if(data[p].j==B.data[p].j)
        {
            C.data[k]=data[p];
            C.data[k].v=data[p].v+B.data[q].v;
            p++;
            q++;
        }
        else if(data[p].j<B.data[q].j)
        {
            C.data[k]=data[p];
            p++;
        }
        else
        {
            C.data[k]=B.data[q];
            q++;
        }
        k++;
    }
    while (p<t)
    {
        C.data[k]=data[p];p++;k++;
    }
    while (p<B.t)
    {
        C.data[k]=B.data[q];q++;k++;
    }
    C.t=k;return C;
}
int main()
{
    SqMatrix aMat,bMat,cMat;
    aMat.Create();
    aMat.showMatrix();
    bMat.Create();
    bMat.showMatrix();
    cMat=aMat+bMat;
    cMat.showMatrix();
    cout<<"\n   Press Enter to exit.";
    getch();
    getch();
    return 0;
}