大家帮我看看Add函数为什么没法工作,谢了啊.
函数Transpose,函数Out,函数NewNode
已经可以正常工作了
这是一个表示稀疏矩阵的三元组,Node为结点,
SanYuanZu为三元组表
#include "stdafx.h"//默认以行优先的顺序
#include <iostream.h>
#include <stdlib.h>
template <class T>
class SanYuanZu;
template <class T>
class Node
{
friend class SanYuanZu<T>;
private:
int row,col;
T value;
};
template <class T>
class SanYuanZu
{
private:
int SRow,SCol,Count;
Node<T> List[100];
public:
SanYuanZu(int row=0,int col=0);
SanYuanZu<T> & Transpose(); //转置
SanYuanZu<T> & Add(SanYuanZu<T> s); //加法
void Out(void) const; //输出
void NewNode(int,int,T); //加入新的结点
};
template <class T>
SanYuanZu<T>::SanYuanZu(int row,int col)
{
if((row<0)||(col<0))
{
cout<<"Can not do such work"<<endl;
return;
}
SRow=row;
SCol=col;
Count=0;
return;
}
template <class T>
SanYuanZu<T> & SanYuanZu<T>::Transpose()
{
SanYuanZu<T> b;
b.SRow=SCol;
b.SCol=SRow;
b.Count=Count;
if(Count>0)
{
int BNumber=0;
for(int i=0;i<SCol;i++)
for(int j=0;j<Count;j++)
if(List[j].col==i)
{
b.List[BNumber].row=i;
b.List[BNumber].col=List[j].row;
b.List[BNumber].value=List[j].value;
BNumber++;
}
}
return b;
}
template <class T>
void SanYuanZu<T>::Out(void) const
{
cout<<"Now display a sanyuanzu"<<endl;
int te=0;
for(int t1=0;t1<SRow;t1++)
for(int t2=0;t2<SCol;t2++)
for(int t3=0;t3<Count;t3++)
{
if((List[t3].row==t1)&&(List[t3].col==t2))
cout<<"_"<<List[t3].value;
}
}
template <class T>
void SanYuanZu<T>::NewNode(int a1,int a2,T item)
{
if((Count>100)||(a1<0)||(a1>=SRow)||(a2<0)||(a2>SCol))
{
cout<<"Can not do such work"<<endl;
return;
}
List[Count].row=a1;
List[Count].col=a2;
List[Count].value=item;
Count++;
cout<<"A new node is created"<<endl;
return;
}
template <class T>
SanYuanZu<T> & SanYuanZu<T>::Add(SanYuanZu<T> s)
{
int ud=0;
int sud=0;
SanYuanZu<T> b;
for(int j=0;j<Count+s.Count;j++)
{
if((List[ud].row==s.List[sud].row)&&(List[ud].col==s.List[sud].col))
{
b.List[j].row=List[ud].row;
b.List[j].col=List[ud].col;
b.List[j].value=List[ud].value+s.List[sud].value;
ud++;
sud++;
j++;
}
else
if(List[ud].row>s.List[sud].row)
{
b.List[j].row=s.List[sud].row;
b.List[j].col=s.List[sud].col;
b.List[j].value=s.List[sud].value;
sud++;
}
else
if(List[ud].row<s.List[sud].row)
{
b.List[j].row=List[ud].row;
b.List[j].col=List[ud].col;
b.List[j].value=List[ud].value;
ud++;
}
}
return b;
}
int main()
{
SanYuanZu<int> si(5,5);
cout<<endl;
si.Out();
cout<<endl;
si.NewNode(1,1,1);
si.NewNode(1,2,2);
si.NewNode(1,3,3);
si.NewNode(1,4,4);
si.NewNode(2,2,2);
si.NewNode(2,3,3);
si.NewNode(2,4,4);
si.NewNode(2,5,5);
si.NewNode(3,3,3);
si.NewNode(3,4,4);
si.NewNode(3,5,5);
cout<<endl;
cout<<endl;
SanYuanZu<int> si2=si.Transpose();
cout<<endl;
cout<<endl;
SanYuanZu<int> si3=si.Add(si2);
cout<<endl;
si3.Out();
cout<<endl;
return 1;
}