#include<iostream.h>
const int size=30;
template<class Datatype>//定义一个类模板
class Seqlist//类
{
public:
Seqlist(){length=0;}//顺序表无参构造
Seqlist(Datatypea[],int n);//顺序表有参构造,使用了数组、整型数据类型
~Seqlist(){}//顺序表析构函数
voidinsert(int i,Datatype x);//顺序表插入
DatatypeDelete(int i);//顺序表删除
Datatypeget(int i);//顺序表按位查找
intlocate(Datatype x);//顺序表按值查找
voidprintlist();//输出顺序表中的数
private:
Datatypedata[size];//一维数组,存放数据元素
intlength;//顺序表的长度
};
template<class Datatype>//类模板的成员函数在类体外定义
Seqlist<Datatype>::Seqlist(Datatypea[],int n)//顺序表有参构造
{
if(n>size)throw"参数非法";
for(inti=0;i<n;i++)
data[i]=a[i];
length=n;
}
template<class Datatype>
void Seqlist<Datatype>::insert(inti,Datatype x)//插入
{if(length>=size)throw"上溢";
if(i<1||i>length+1)throw"位置";
for(int j=length;j>=i;j--)
data[j]=data[j-1];
data[i-1]=x;
length++;
}
template<class Datatype>
DatatypeSeqlist<Datatype>::Delete(int i)//删除
{ Datatype x;
if(length==0)throw"下溢";
if(i<1||i>length)throw"位置";
x=data[i-1];
for(intj=i;j<length;j++)
data[j-1]=data[j];
length--;
returnx;
}
template<class Datatype>
Datatype Seqlist<Datatype>::get(inti)//按位查找
{if(i<1||i>length)throw"查找位置非法";
else return data[i-1];
}
template<class Datatype>//按值查找
intSeqlist<Datatype>::locate(Datatype x)
{for(int i=0;i<length;i++)
if(data[i]==x)return i+1;
return 0;
}
template<class Datatype>
void Seqlist<Datatype>::printlist()//遍历
{
for(inti=0;i<length;i++)
cout<<data[i]<<"";
cout<<endl;
}
int main()//主函数
{inta[20]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
Seqlist<int>seq(a,20);//定义一个名为seq的对象
cout<<"顺序表是:"<<endl;
seq.printlist();
cout<<endl<<"在第四个位置插入0,顺序表改为:"<<endl;
seq.insert(4,0);
seq.printlist();
cout<<endl<<"删除第六位的数,顺序表改为:"<<endl;
seq.Delete(6);
seq.printlist();
cout<<endl<<"查找到第二位的数是:";
seq.get(2);
cout<<seq.get(2)<<endl;
cout<<endl<<"数值为8的数在:第";
cout<<seq.locate(8)<<"位"<<endl;
cout<<endl<<"最终的顺序表是:"<<endl;
seq.printlist();
return 0;
总结:这次写顺序表主要用到类模板和数组,整个程序实现了顺序表的插入、删除、按位查找以及按值查找的功能。
因为使用了C++语言,写这个顺序表需要用到类模板,这个是之前还没有学过的,通过上网查资料和翻找书本,对类模板进行了一定的了解,通过写这个顺序表,我对C++的定义类和对象有了更深刻的认识,对于顺序表如何进行插入、删除和查找也有了更深的理解。不足之处是这个顺序表是最基本的顺序表,功能不够多。在写程序时对main函数的写法存在一些疑问。