结构体数组转换wen'ti

如何将 ReadArray 函数中 new 改在 main 函数中实现
将 ReadArray函数中结构体数组的指针访问改用数组下标访问

#include<iostream>
#include<fstream>
#include<string>
#include<algorithm>
using namespace std;
struct Student
{
    unsigned long long int ID;
    string name;
    bool sex;
    unsigned short int grade[3];
};
Student* ReadArray(int& RecordNum)
{
    ifstream infile("学生成绩表.txt");
    if(infile==0) return 0;
    infile>>RecordNum;
    Student *p=new Student[RecordNum];
    Student *head=p;
    int temp;
    for(int i=0;i<RecordNum;i++)
    {
        infile>>temp;
        infile>>p->ID;
        infile>>p->name;
        infile>>p->sex;
        for(int j=0;j<3;j++)
        {
            infile>>p->grade[j];
        }
        p++;
    }
    infile.close();
    return head;
}
void Show(Student a[],int num)
{
    int sn=1;
    for(int i=0;i<num;i++)
    {
        cout<<" "<<sn++<<" ";
        cout<<a[i].ID<<" "<<a[i].name<<" ";
        if(a[i].sex)cout<<"男"<<" ";
        else        cout<<"女"<<" ";
        for(int j=0;j<3;j++)
            cout<<" "<<a[i].grade[j]<<" ";
        cout<<endl;
    }
}
int cmp(const void *a,const void *b)
{
    return(*(Student*)a).grade[2]-(*(Student*)b).grade[2];
}
bool myGreater(Student&elem1,Student& elem2)
{
    return(elem1.grade[2]>elem2.grade[2]);
}
int main()
{
    int N;
    Student *A=ReadArray(N);
    if(A==0)
    {
        cout<<"文件打开失败!\n";
        return 0;
    }
    cout<<"序号"<<"\t学号"<<"\t   姓名"<<"性别"<<"高数"<<"英语"<<"C++"<<endl;
    Show(A,N);
    qsort(A,N,sizeof(*A),cmp);
    cout<<"用qstor函数对C++成绩排升序:\n";
    Show(A,N);
    sort(A,N+A,myGreater);
    cout<<"用sort函数对C++成绩进行降序:\n";
    Show(A,N);
    delete[]A;
    system("pause");
    return 0;
}
c++

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问