题目描述
查找和排序 :输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。
输入例子:
3
0
fang 90
yang 50
ning 70
输出例子:
fang 90
ning 70
yang 50
【代码】
- #include<iostream>
- #include<string>
- #include<vector>
- #include<algorithm>
- using namespace std;
-
- struct student
- {
- string name;
- int score;
- };
- bool cmp0(const student &a, const student &b) //高到低
- {
- return a.score > b.score;
- }
- bool cmp1(const student &a, const student &b) //低到高
- {
- return a.score < b.score;
- }
-
- int main()
- {
- int n, cmp;
- while(cin>>n>>cmp)
- {
- vector<student> stu(n);
- for(int i=0; i<n; i++)
- cin>> stu[i].name >> stu[i].score;
- if(cmp==0)
- stable_sort(stu.begin(), stu.end(), cmp0);
- else
- stable_sort(stu.begin(), stu.end(), cmp1);
- for(int i=0; i<n; i++)
- cout<< stu[i].name <<" "<<stu[i].score<<endl;
- }
- return 0;
- }
****************************************** 相关 *****************************************************
题目描述
用一维数组存储学号和成绩,然后,按成绩排序输出。
输入描述:
输入第一行包括一个整数N(1<=N<=100),代表学生的个数。
接下来的N行每行包括两个整数p和q,分别代表每个学生的学号和成绩。
输出描述:
按照学生的成绩从小到大进行排序,并将排序后的学生信息打印出来。
如果学生的成绩相同,则按照学号的大小进行从小到大排序。
输入例子:
3
1 90
2 87
3 92
输出例子:
2 87
1 90
3 92
- #include<iostream>
- #include<string>
- #include<vector>
- #include<algorithm>
- using namespace std;
-
- struct student
- {
- int number;
- int score;
- };
- bool comp(const student &a, const student &b)
- {
- if(a.score != b.score)
- return a.score < b.score;
- else
- return a.number < b.number;
- }
-
- int main()
- {
- student stu;
- vector<student> v;
- int n;
- while(cin>>n)
- {
- for(int i=0; i<n; i++)
- {
- cin>>stu.number>>stu.score;
- v.push_back(stu);
- }
- sort(v.begin(), v.end(), comp);
- vector<student>::iterator it;
- for(it=v.begin(); it<v.end(); it++)
- {
- cout<<(*it).number<<" "<<(*it).score<<endl;
- }
- }
- return 0;
- }