博客
关于我
sort()排序
阅读量:662 次
发布时间:2019-03-15

本文共 1288 字,大约阅读时间需要 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 9LiGang 18WangLei 20XiaoWang 20

转载地址:http://kydmz.baihongyu.com/

你可能感兴趣的文章
python+pytest接口自动化:接口测试
查看>>
Python+requests+unittest执行接口自动化测试详情
查看>>
Python+requests+unittest执行接口自动化测试详情
查看>>
python+requests+unittest执行自动化接口测试!
查看>>
Python+Requests编码识别Bug
查看>>
python函数编写_[零基础学python]传说中的函数编写条规
查看>>
Python+selenium —— UI自动化之鼠标操作
查看>>
python函数注释,参数后面加冒号:,函数后面的箭头→是什么?
查看>>
Python+Selenium+Threading进行兼容性测试
查看>>
Python+selenium+unittest的GUI自动化框架实现
查看>>
python函数拟合不规则曲线_Python计算&绘图——曲线拟合问题(转)
查看>>
python函数定义的基本格式_零基础学python-2.19 定义函数、调用函数与默认参数
查看>>
Python+Selenium之数据驱动测试的实现
查看>>
python函数定义与使用+返回值简解
查看>>
Python+Selenium登录
查看>>
Python日期时间模块
查看>>
Python函数合集:足足68个内置函数请收好!
查看>>
Python+Selenium自动化测试项目实战
查看>>
Python+Selenium自动化测试项目实战【建议收藏】
查看>>
Python+Selenium自动化测试:Page Object模式
查看>>