欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实验三顺序表

程序员文章站 2024-03-20 14:04:16
...
#include <iostream>    
using namespace std;    
const int N=5;    
class Student{    
private:    
    int scores[N];    
    int length;    
public:    
    Student(int score[],int n);    
    ~Student(){}    
    void Insert(int i,int x);    
    int Delete(int i);    
    int Get(int i);    
    int Locate(int x);    
    void Show();    
};    
Student::Student(int score[],int n){    
    if (n>N) throw "参数非法";    
    for (int i=0;i<n;i++)    
        scores[i]=score[i];    
    length=n;    
}    
void Student::Insert(int i,int x){    
    if (lenght>N) throw "上溢";    
    if (i<0||i>length+1) throw "位置非法";    
    for (int j=length;j>=i;j--)    
        scores[j]=scores[j-1];    
    scores[i-1]=x;    
    length++;    
}    
int Student::Delete(int i){    
    if (length<0) throw "下溢";    
    if (i<0||i>length+1) throw "位置非法";    
    int x=scores[i-1];    
    for (int j=i-1;j<length-1;j++)    
        scores[j]=scores[j+1];    
    length--;    
    return x;    
}    
int Student::Get(int i){    
    return scores[i-1];    
}    
int Student::Locate(int x){    
    int n;    
    for (int i=0;i<length;i++)    
        if (scores[i]==x)    
            n=i+1;    
        return n;    
}    
void Student::Show(){    
    for (int i=0;i<length;i++)    
        cout<<scores[i]<<' ';    
    cout<<endl;    
}    
    
int main (){    
    int a[3]={70,80,95};    
    Student S(a,3);    
    cout<<"原表:"<<endl;    
    S.Show();    
    cout<<"在第3位插入99:"<<endl;    
    S.Insert(3,99);    
    cout<<"插入后:"<<endl;    
    S.Show();    
    cout<<"删除第2位:"<<endl;    
    S.Delete(2);    
    cout<<"删除后:"<<endl;    
    S.Show();    
cout<<"查80分的位置:"<<S.Locate(80)<<','<<"查第2位的成绩:"<<S.Get(2)<<endl;    
    return 0;    }