#include <iostream> using namespace std; const int maxsize = 7; template <class datatype> class scorelist { private: datatype stu[maxsize]; int length; public: scorelist() { length = 0; } ~scorelist(){} scorelist(datatype a[], int n); double locate(int i); void insert(int i, datatype x); void printlist(); }; template<class datatype> scorelist<datatype>::scorelist(datatype a[],int n) { int i; if (n > maxsize) throw"参数非法"; for (i = 0; i < n; i++) stu[i] = a[i]; length=n; } template<class datatype> double scorelist<datatype>::locate(int i) //按位查找成绩 { if (i<1 && i>length) throw"查找位置非法"; else return stu[i - 1]; } template<class datatype> void scorelist<datatype>::insert(int i, datatype x) //插入成绩 { if (length >= maxsize) throw"上溢"; if (i<1 || i>length + 1) throw"位置非法"; for (int j = length; j >= i; j--) stu[j] = stu[j - 1]; stu[i - 1] = x; length++; } template<class datatype> void scorelist<datatype>::printlist() { for(int i=0;i<length;i++) cout<<stu[i]<<" "; cout<<endl; } void main() { double stud[5] = { 98.6,85.7,65.9,70.2,73.4}; scorelist<double>student(stud,5); student.printlist(); cout<<"插入新成绩后:"<<endl; try { student.insert(3,98.6); } catch(char *s) { cout<<s<<endl; } student.printlist(); cout<<"第三个成绩为:"<<endl; cout<<student.locate(3)<<endl; }
实验3:顺序表
猜你喜欢
转载自blog.csdn.net/u011633428/article/details/80173018
今日推荐
周排行