1、排序方法:

sort(数组起始指针,数组尾指针,排序规则);

数组起始指针,数组尾指针是左闭右开

排序规则可以省略,也可以用系统的,也可以自己写

2、例子:

int a[]={9,2,4,5,10,7,30};

sort(a,a+7);

这是默认的对数组从小到大排列
#include <iostream> #include <algorithm> #include <string> using namespace std;
//结构体排序一 //按姓名从小到大排序,姓名一样,按年龄从小到大排序 struct student{ string name;//姓名 int age;
//年龄 }; int comp(const student &s1,const student &s2){//自己定义的排序规则 if
(s1.name==s2.name){return s1.age<s2.age; } else{ return s1.name<s2.name; } }
//结构体排序二 //按姓名从小到大排序,姓名一样,按年龄从小到大排序 struct student2{ string name;//姓名 int age;
//年龄 bool operator < (const student2 & s2) const {//符号重载 if(name==s2.name){
return age<s2.age; } else{ return name<s2.name; } } }; int main(){ //普通数组排序 int
a[]={9,2,4,5,10,7,30}; sort(a,a+7);//省略掉排序规则的形式,默认从小到大 sort(a,a+7,less<int>());
//用系统的排序规则,从小到大 sort(a,a+7,greater<int>());//用系统的排序规则,从大到小 for(int i=0;i<7;i++){
cout<<a[i]<<" "; } cout<<endl; //结构体数组排序一 student s[100]; s[0].name="zhangsan"
;s[0].age=18; s[1].name="zhangsan";s[1].age=19; s[2].name="lisi";s[2].age=20;
sort(s,s+3,comp);//左闭右开,所以是对s[0]到s[2]排序 for(int i=0;i<3;i++){ cout<<s[i].name<<
" "<<s[i].age<<endl; } //结构体数组排序二:符合重载 student2 s2[100]; s2[0].name="zhangsan"
;s2[0].age=18; s2[1].name="zhangsan";s2[1].age=19; s2[2].name="lisi";s2[2].age=
20; sort(s2,s2+3);//左闭右开,所以是对s[0]到s[2]排序 for(int i=0;i<3;i++){ cout
<<s2[i].name<<" "<<s2[i].age<<endl; } return 0; } /* 30 10 9 7 5 4 2 lisi 20
zhangsan 18 zhangsan 19 lisi 20 zhangsan 18 zhangsan 19 */

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信