本文共 1330 字,大约阅读时间需要 4 分钟。
一维整数数组排序
我们可以使用C++库中的sort函数对一维数组进行排序。sort函数的原型为sort(begin, end, [比较函數]). 如果没有提供比较函數,排序默认是从小到大进行的。
例如,以下代码会对数组{1, 5, 2, 9, 11, 6, 7}进行从小到大的排序:
#include <bits/stdc++.h> using namespace std; int main() { int num[] = {1, 5, 2, 9, 11, 6, 7}; int length = sizeof(num) / sizeof(int); sort(num, num + length); for(int i : num) { printf("%d ", i); } }
运行结果:
1 2 5 6 7 9 11
如果想对数组进行从大到小的排序,我们可以自定义一个比较函数。例如:
#include <bits/stdc++.h> using namespace std; bool cmp(int A, int B) { return A > B; } int main() { int num[] = {1, 5, 2, 9, 11, 6, 7}; int length = sizeof(num) / sizeof(int); sort(num, num + length, cmp); for(int i : num) { printf("%d ", i); } }
运行结果:
11 9 7 6 5 2 1
结构体排序
我们已经了解了如何通过自定义比较函数来对一维数组排序。接下来我们来看看如何对结构体数组进行排序。结构体数组的排序依赖于我们自定义的比较函数。
假设我们有如下结构体:
struct student { string name; int age; };
我们需要对结构体数组进行排序,可以根据年龄从小到大排序,如果年龄相同则按照姓名从大到小排序。我们可以定义如下比较函数:
#include <bits/stdc++.h> using namespace std; bool cmp(student A, student B) { if(A.age != B.age) { return A.age < B.age; } return A.name > B.name; }
主函数部分:
int main() { student s[4]; s[0].name = "WangLei"; s[0].age = 20; s[1].name = "XiaoWang"; s[1].age = 20; s[2].name = "LiGang"; s[2].age = 18; s[3].name = "ZhangSan"; s[3].age = 9;
sort(s, s+4, cmp);for(student i : s) { cout << i.name << " " << i.age << endl;} }
运行结果:
ZhangSan 9 LiGang 18 WangLei 20 XiaoWang 20
转载地址:http://kydmz.baihongyu.com/