c++ STL的简单用法总结(sort)
2022/1/27 14:07:20
本文主要是介绍c++ STL的简单用法总结(sort),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
用法1:
sort(数组名+n1,数组名+n2) ;这种就是简单的从小到大排序
(n1是开始排序位置的下标,n2是结尾位置的下标+1)
用法2:
sort(数组名+n1,数组名+n2,greater<T>);(T是要排序的数据类型)从大到小排序
用法3;
sort(数组名+n1,数组名+n2,排序规则结构名());这种就比较厉害了
这里举了一个例子 sort最强大的功能 :对结构进行排序 并且可以自定义排序规则
代码如下
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm>//使用STL算法需要引用的头文件 using namespace std; typedef struct { char name[20]; int id; double gpa; }student;//定义一个结构 包含学生姓名 id gpa; student s[]={ {"JACK",112,3.4},{"MARRY",102,3.8},{"MARRY",117,3.9}, {"ALA",333,3.5},{"ZERO",101,4.0} };//创建一个结构数组 //定义排序规则 1(结构类型) //按名字字母排序 struct studentrule1{ bool operator()(const student&s1,const student&s2)const{ if(stricmp(s1.name,s2.name)<0)//stricmp和strcmp相比 stricmp忽略大小写字母顺序排序 { return true;//如果s1.name比s2.name小的话 s1放在s2的前面 }else{ return false; } } }; //定义排序规则2(结构类型) //按学生id排序 struct studentrule2{ bool operator()(const student&s1,const student&s2)const{ return s1.id<s2.id;//如果s1.id<s2.id s1在s2的前面 } }; //定义排序规则3(结构类型) //按学生gpa从高到低排序 struct studentrule3{ bool operator()(const student&s1,const student&s2)const{ return s1.gpa>s2.gpa;//如果s1.gpa>s2.gpa s1放在s2的前面 } }; //定义一个打印结构的函数 void print(student s[],int len){ for(int i=0;i<len;i++){ cout<<"("<<s[i].name<<","<<s[i].id <<","<<s[i].gpa<<")"<<endl; } return ; } int main(){ int n=sizeof(s)/sizeof(s[0]); cout<<"1)"; sort(s,s+n,studentrule1());print(s,n);//注意:sort(数组名+n1,数组名+n2,排序规则)n2是要排序的元素个数 //也就是末尾下标+1,而不是最后一个下标 //n1是开始排序位置的下标 cout<<endl<<"2)"; sort(s,s+n,studentrule2());print(s,n); cout<<endl<<"3)"; sort(s,s+n,studentrule3());print(s,n); return 0; }
运行结果:
这篇关于c++ STL的简单用法总结(sort)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-29Elasticsearch慢查询日志配置
- 2024-05-29揭秘华为如此多成功项目的产品关键——Charter模板
- 2024-05-29海外IDC业务拓展的7大挑战
- 2024-05-29InLine Chat功能优化对标Github Copilot,CodeGeeX带来更高效、更直观的编程体验!
- 2024-05-29CodeGeeX 智能编程助手 6 项功能升级,在Visual Studio插件市场霸榜2周!
- 2024-05-29AutoMQ 生态集成 Apache Doris
- 2024-05-292024年IDC行业的深度挖掘:机遇、挑战与未来展望
- 2024-05-29五款扩展组件齐发 —— Volcano、Keda、Crane-scheduler 等,邀你体验
- 2024-05-29AutoMQ 对象存储数据高效组织的秘密: Compaction
- 2024-05-29活动预告|来 GIAC 大会听大数据降本利器:AutoMQ 基于云原生重新设计的 Kafka