注册 登录
编程论坛 C++教室

新手 如何用C++编写类实现相关信息输出

llllc 发布于 2021-04-05 20:35, 2171 次点击
有4个学生组队参加某比赛,每个学生信息包含学号,姓名,个人成绩,4个学生有一共同团队成绩。
①编写一学生类完成其定义实现,学号唯一(6位);
②编写主程序模拟生成4个学生给其赋值、完成相关信息的输出,按个人成绩排序从高到低输出每个学生的所有信息,成绩相同则按学号大小。
学生的个人信息随机输入,怎么实现排序或按大小输出呢
4 回复
#2
林月儿2021-04-05 22:05
写多少了?
#3
llllc2021-04-05 23:17
回复 2楼 林月儿
包含四个学生
#4
apull2021-04-05 23:31
楼上这个回答绝了
#5
林月儿2021-04-05 23:39
程序代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Student {
    private:
        string no;
        string name;
        int score;
    public:
        Student(){}
        Student(string no,string name,int score);
        void display();
        static bool comparator(Student a,Student b){
            if(a.score!=b.score){
                return a.score<b.score;
            }
            return a.no<b.no;
        }
        
};

Student::Student(string _no,string _name,int _score){
    no=_no;
    name=_name;
    score=_score;
}
void Student::display(){
    cout<<no<<'\t'<<name<<'\t'<<score<<endl;
}
int main() {
    vector<Student> stus;
    for(int i=0;i<4;i++){
        string no="";
        cout<<"请输入第"<<(i+1)<<"个学生的学号:";
        cin>>no;
        string name="";
        cout<<"请输入第"<<(i+1)<<"个学生的姓名:";
        cin>>name;
        int score=0;
        cout<<"请输入第"<<(i+1)<<"个学生的成绩:";
        cin>>score;
        Student stuEle(no,name,score);
        stus.push_back(stuEle);
        cout<<endl;
    }
    sort(stus.begin(),stus.end(),Student::comparator);
    cout<<"No\tName\tScore"<<endl;
    for(int i=0;i<stus.size();i++){
        stus[i].display();
    }
     
    return 0;
}


[此贴子已经被作者于2021-4-5 23:49编辑过]

1