#include"iostream.h"
#include"string.h"
//順序表的定義
template<class T> class SeqList
{
T *data;
int MaxSize;//最長度大
int last;//當前最後元素下標
public:
SeqList(int);
~SeqList()
{
delete[] data;
}
int Length() const
{
return last+1;
}
int Find(T &x);//查找
int Insert(T &x,int i);//插入
int Remove(T &x);//刪除
void Display();//打印
int IsEmpty()
{
return last==-1;
}
int IsFull()
{
return last==MaxSize-1;
}
T Get(int i)//獲取
{
if(i>last||i<0) {cout<<"位置異常"<<endl; }
else return data[i];
}
};
//順序表的實現
template<class T>
SeqList<T>::SeqList(int sz)
{
if(sz>0)
{
MaxSize=sz;
last=-1;
data=new T[MaxSize];
if(data==NULL)
{
MaxSize=0;
last=-1;
return;
}
}
}
template<class T>
int SeqList<T>::Find(T &x)
{
int i;
for(i=0;i<=last;i++)
if (data[i]==x)
return i;
return -1;
}
template<class T>
int SeqList<T>::Insert(T &x,int i)
{
if(i<0||i>last+1||last==MaxSize-1)
return 0;
else
{
last++;
for(int j=last;j>i;j--)
data[j]=data[j-1];
data[i]=x;
return 1;
}
}
template<class T>
int SeqList<T>::Remove(T &x)
{
int i=Find(x);
if(i>=0)
{
last--;
for(int j=i;j<=last;j++)
data[j]=data[j+1];
return 1;
}
return 0;
}
template<class T>
void SeqList<T>::Display()
{
for(int i=0;i<=last;i++)
{
cout<<data[i]<<endl;
}
}
//Student類定義
class Student
{
public:
int id;
char name[20];
int year;
int score;
bool operator==(const Student &);
};
//Student類的實現
bool Student::operator==(const Student &s)//重載==運算符
{
if(this==&s)
return true;
if((id==s.id)&&(strcmp(name,s.name)==0)&&(year==s.year)&&(score==s.score))
return true;
else return false;
}
ostream& operator<<(ostream &os,Student &s)//重載<<運算符
{
os<<s.id<<" "<<s.name<<" "<<s.year<<" "<<s.score<<endl;
return os;
}
istream& operator>>(istream &is,Student &s)//重載>>運算符
{
cout<<"請輸入此學生的學號,姓名,入學年份,分數"<<endl;
is>>s.id>>s.name>>s.year>>s.score;
return is;
}
//主函數
void main()
{
int i,j,k,m;
SeqList<Student> S(10);
Student S1,S2,S3,S4,S5,S6,S7,S8;
int flag=0;
while(flag==0)
{
cout<<"順序表的實現(模板類)"<<endl;
cout<<"************************************"<<endl;
cout<<"* 1:創建表格 *"<<endl;
cout<<"* 2:插入記錄 *"<<endl;
cout<<"* 3:刪除記錄 *"<<endl;
cout<<"* 4:查詢記錄 *"<<endl;
cout<<"* 5:打印表格 *"<<endl;
cout<<"* 6:exit.退出 *"<<endl;
cout<<"************************************"<<endl;
cout<<"請輸入您的選擇:";
cin>>j;
switch(j)
{
case 1:
cin>>S1>>S2;
S.Insert(S1,0);
S.Insert(S2,1);
break;
case 2:
cin>>S3;
i=S.Find(S1);
S.Insert(S3,i+1);
cin>>S4;
S.Insert(S4,i);
i=S.Find(S2);
cin>>S5;
S.Insert(S5,i+1);
break;
case 3:
S6=S.Get(0);
S.Remove(S6);
k=S.Length();
S7=S.Get(k-1);
S.Remove(S7);
break;
case 4:
cout<<"請輸入您要查詢的記錄:";
cin>>S8;
m=S.Find(S8);
if(m<0)
cout<<"不存在此記錄!";
else
cout<<"存在記錄:"<<S8;
break;
case 5:
S.Display();
break;
case 6:
flag=1;
break;
default:
cout<<"沒有此命令!"<<endl;
}
}
}