不想自己写排序怎么办?那就用algorithm库里的sort函数吧。
sort函数采用的原理是快速排序,需要指出的是,sort函数默认采用的是升序排序,如果想要降序排序,需要自己定义一个bool函数。
有以下用法:
一、对vector数组和普通数组的排序
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
//降序函数
bool cmp(int a, int b){
return a>b;
}
int main()
{
srand((int)time(0));//随机数种子
vector<int> arr;
for (int i = 0; i < 10; i++)
{
arr.push_back(rand() % 100);//将100以内的随机数加到vector数组里
}
//从小到大排序(升序)
sort(arr.begin(),arr.end()); //sort(数组首地址,数组末地址)
//如果为普通数组,那么:sort(数组名,数组名+n) n为数组长度
for (auto it = arr.begin(); it != arr.end(); it++)
{
cout<<' '<<*it;
}
cout<<endl;
//从大到小排序(降序)
sort(arr.begin(),arr.end(), cmp);
for (auto it = arr.begin(); it != arr.end(); it++)
{
cout<<' '<<*it;
}
return 0;
}
二、对结构体数组的排序(同样适用于类)
关于这里的内容,我想从一道题引入:
1004 成绩排名 (20 分)
读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
输入格式:
每个测试输入包含 1 个测试用例,格式为
第 1 行:正整数 n
第 2 行:第 1 个学生的姓名 学号 成绩
第 3 行:第 2 个学生的姓名 学号 成绩
…
…
…
第 n+1 行:第 n 个学生的姓名 学号 成绩
其中姓名和学号均为不超过 10 个字符的字符串,成绩为 0 到 100 之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。
输出格式:
对每个测试用例输出 2 行,第 1 行是成绩最高学生的姓名和学号,第 2 行是成绩最低学生的姓名和学号,字符串间有 1 空格。
输入样例:
3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
输出样例:
Mike CS991301
Joe Math990112
思路其实很简单,定义一个学生类,包含以下成员:{姓名,学号,成绩},
然后在main()函数新建一个学生数组stu student[MAXN];,
用户输入学生信息,利用sort函数排序,但这里的sort略有不同,
无论升序还是降序都得自己写一个cmp函数
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
using namespace std;
const int MAXN = 100;
struct stu
{
string name;
string id;
int cj;
};
bool cmp(stu x, stu y) //注意,这里的类型就不是int了,而是stu,因为你要对stu类型的数据进行排序
{
return x.cj < y.cj; //根据stu里的成绩cj排序
}
int main()
{
stu student[MAXN];
int n;
cin >> n;
//输入信息
for (int i = 0; i < n; i++)
cin >> student[i].name >> student[i].id >> student[i].cj;
//排序,必须有cmp
sort(student, student + n, cmp);
//最后输出最高分及其名字,最低分同理
cout << student[n - 1].name << ' ' << student[n - 1].id;
cout << endl;
cout << student[0].name << ' ' << student[0].id;
return 0;
}