使用list容器对学生成绩信息进行存储,然后分别对分数进行排序,再输出。
排序优先级规则:
- 总分一样,数学高则排名高
- 数学一样,英语高则排名高
- 英语一样,专业课成绩高则高,以此类推
#include <iostream>
#include <vector>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
//学生类
class Person
{
public:
string m_Name; //姓名
string m_school; //拟报考院校
int m_Score; //总成绩
int m_politics; //政治成绩
int m_english; //英语成绩
int m_math; //数学成绩
int m_major; //专业课成绩
int m_num; //准考证号
Person(int num, string sname, string name, int politics, int english, int math, int major) //构造函数
{
this->m_num = num;
this->m_school = sname;
this->m_Name = name;
this->m_Score = politics + english + math + major; //总分等于各科成绩之和
this->m_politics = politics;
this->m_english = english;
this->m_math = math;
this->m_major = major;
}
};
//定义一个比较函数,总分一样数学高,排名高,数学一样,
//英语高则排名高,英语一样,专业课成绩高则高,以此类推
bool compare(Person &h1, Person &h2)
{
if (h1.m_Score != h2.m_Score)
{
return h1.m_Score > h2.m_Score;
}
else if (h1.m_math != h2.m_math)
{
return h1.m_math > h2.m_math;
}
else if (h1.m_english != h2.m_english)
{
return h1.m_english > h2.m_english;
}
else
{
return h1.m_major > h2.m_major;
}
}
void test01()
{
//创建一个list链表
list<Person> l;
//创建12个对象,并赋值
Person p1(101, "北京大学", "小师", 65, 64, 125, 130);
Person p2(102, "天津大学", "小白", 65, 68, 120, 135);
Person p3(103, "清华大学", "小赵", 80, 78, 108, 101);
Person p4(104, "浙江大学", "小王", 55, 54, 95, 135);
Person p5(105, "武汉大学", "小黄", 80, 70, 108, 109);
Person p6(106, "上海交通大学", "小罗", 67, 60, 115, 110);
Person p7(107, "北京航空航天大学", "小刘", 59, 61, 105, 120);
Person p8(108, "华中科技大学", "小张", 55, 63, 110, 115);
Person p9(109, "西安交通大学", "小唐", 62, 80, 128, 141);
Person p10(110, "电子科技大学", "小郭", 65, 64, 115, 135);
Person p11(111, "北京理工大学", "小李", 60, 78, 80, 139);
Person p12(112, "复旦大学", "小鹿", 60, 70, 85, 130);
//将这十二个人的信息尾插进链表
l.push_back(p1);
l.push_back(p2);
l.push_back(p3);
l.push_back(p4);
l.push_back(p5);
l.push_back(p6);
l.push_back(p7);
l.push_back(p8);
l.push_back(p9);
l.push_back(p10);
l.push_back(p11);
l.push_back(p12);
//进行排序前的输出
for (list<Person>::iterator it = l.begin(); it != l.end(); it++)
{
cout << "准考证号:" << it->m_num << " 姓名:" << it->m_Name << " 总分: " << it->m_Score << " 政治: " << it->m_politics << " 英语:"
<< it->m_english << " 数学:" << it->m_math << " 专业课:" << it->m_major << " 拟报考院校:" << it->m_school << endl;
}
//排序
cout << "---------------------------------------------------------------------------------------------------" << endl;
cout << "| 排序后 |" << endl;
cout << "---------------------------------------------------------------------------------------------------" << endl;
l.sort(compare); //排序操作,sort函数需要调用
for (list<Person>::iterator it = l.begin(); it != l.end(); it++)
{
cout << "准考证号:" << it->m_num << " 姓名:" << it->m_Name << " 总分: " << it->m_Score << " 政治: " << it->m_politics << " 英语:"
<< it->m_english << " 数学:" << it->m_math << " 专业课:" << it->m_major << " 拟报考院校:" << it->m_school << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}