成绩排序
思路:用algorithm的sort函数对键值对进行排序(需自定义比较函数,这里是我需要学习的),最后输出。
自定义的比较函数逻辑,比如比较整数s1和s2,如果要使s1小于s2时是真,则return s1<s2;使s1大于s2时是真,则return s1>s2。
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
struct student
{
string name;
int score;
int num;
};
int cmp1(student &s1, student &s2)
{
if (s1.score == s2.score)
return s1.num < s2.num;
else
return s1.score < s2.score;
}
int cmp0(student &s1, student &s2)
{
if (s1.score == s2.score)
return s1.num < s2.num;
else
return s1.score > s2.score;
}
int main()
{
int count, method;
while (cin >> count && cin >> method) {
student *list = new student[count];
for (int i = 0; i < count; ++i) {
cin >> list[i].name >> list[i].score;
list[i].num = i;
}
//排序
if (method == 1)//升序
sort(list, list + count, cmp1);
else//降序
sort(list, list + count, cmp0);
for (int i = 0; i < count; ++i)
cout << list[i].name << " " << list[i].score << endl;
}
system("pause");
return 0;
}


京公网安备 11010502036488号