1.建立一个由n个学生成绩的顺序表,实现对数据的插入,删除,查找等操作。
源代码:
#ifndef Student_H
#define Student_Hconst int MaxSize=100;
class Student
{
public:
Student(){length=0;}
Student(double a[],int n);
~Student(){}
void Insert(int i,int x);
double Delete(int i);
double Locate(int x);
void Print();
private:
double data[MaxSize];
int length;
};
#endif
#include<iostream.h>
#include"Student.h"Student::Student(double a[],int n)
{
if(n>MaxSize) throw"成绩表已满";
for(int i=0;i<n;i++)
data[i]=a[i];
length=n;
}
void Student::Insert(int i,int 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++;
}
double Student::Delete(int i)
{
if(length==0) throw"成绩表为空";
if(i<1||i>length+1) throw"位置非法";
double x=data[i-1];
for(int j=i;j<length;j++)
data[j-1]=data[j];
length--;
return x;
}
double Student::Locate(int x)
{
for(int i=0;i<length;i++)
if(data[i]==x) return i+1;
return 0;
}
void Student::Print()
{
for(int i=0;i<length;i++)
cout<<data[i]<<" ";
cout<<endl;
}
#include<iostream.h>
#include"Student.h"
void main()
{
double s[5]={85.5,67,48,91,76};
Student S(s,5);
cout<<"输出所有学生成绩:"<<endl;
S.Print();
try
{
S.Insert(3,84);
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<endl;
cout<<"修改后的学生成绩:"<<endl;
S.Print();
cout<<endl;
cout<<"查找成绩为84的位置:";
cout<<S.Locate(84)<<endl;
cout<<endl;
cout<<"删除前的成绩:"<<endl;
S.Print();
try
{
S.Delete(2);
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<endl;
cout<<"输出后的成绩:"<<endl;
S.Print();
}
运行结果: