顺序表是用一段地址连续的储存单元依次储存线性表的数据元素,我打算借鉴书本用C++写一个小顺序表记录10个人的数学成绩。
源代码:
头文件:
#include<iostream>
#include<fstream>
using namespace std;
定义模板类SeqList:
const int MaxSize=20;
template<class DataType>
class SeqList
{
public:
SeqList(){Length=0;}
SeqList(DataType a[],int n);
~SeqList(){}
DataType Get(int i);
int Locate(DataType x);
void Insert(int i,DataType x);
DataType Delete(int i);
void PrintList();
private:
DataType data[MaxSize];
int Length;
};
依次定义已声明的函数:
template<class DataType>
SeqList<DataType>::SeqList(DataType a[],int n)
{
if(n>MaxSize)throw"参数非法";
for(int i = 0;i<n;i++)
data[i]=a[i];
Length=n;
}
template<class DataType>
DataType SeqList<DataType>::Get(int i)
{
if(i<1&&i>Length) throw"查找位置非法";
else return data[i-1];
}
template<class DataType>
int SeqList<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>::Insert(int i,DataType x)
{
if(Length>=MaxSize) 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>
DataType SeqList<DataType>::Delete(int i)
{
if(Length==0)throw"下溢";
if(i<1||i>Length)throw"位置";
DataType x=data[i-1];
for(int j=i;j<Length;j++)
data[j-1]=data[j];
Length--;
return x;
}
template<class DataType>
void SeqList<DataType>::PrintList()
{
for(int i=0;i<Length;i++)
cout<<data[i]<<" ";
}
主函数(具体引用一段数据):
void main()
{
int ms[10]={100,98,97,96,92,86,84,82,76,73};
SeqList<int>list(ms,10);
cout<<"10人数学成绩:"<<endl;
list.PrintList();
cout<<endl;
cout<<"排名第7的成绩为:"<<endl;
cout<<list.Get(7)<<endl;
cout<<"86分的同学排名为:"<<endl;
cout<<list.Locate(86)<<endl;
cout<<"尾端插入成绩为56且倒数第一:"<<endl;
list.Insert(11,56);
cout<<"当前表为:"<<endl;
list.PrintList();
cout<<endl;
cout<<"删除不及格成绩"<<endl;
list.Delete(11);
cout<<"当前表为:"<<endl;
list.PrintList();
cout<<endl;
}
运行与测试结果:
总结与心得:
之前学c++学得最不好的就是模板,所以这次任务开始不太顺利,不过静下心来看书上的实例就理解得很快。以前写过双链表,所以理解好后做起来也不太费力。程序中若有不妥当的地方请读者耐心指出。