C++sort函数的各种用法
C++中有很多好用的库函数
用起来方便又快捷
最喜欢sort这个函数
但是经常记混它的用法
在此总结一下
方便学习
Sort()函数是C++一种排序方法之一,学会了这种方法也打消我学习C++以来使用的冒泡排序和选择排序所带来的执行效率不高的问题!因为它使用的排序方法是类似于快排的方法,时间复杂度为n*log2(n),执行效率较高。
(1)Sort()函数的头文件为#include<algorithm>
(2)Sort函数有三个参数:
第一个是要排序的数组的起始地址。
第二个是结束地址(最后一位要排序的地址)
第三个参数是排序的方法,可以从小到大也可以是从大到小,当不写第三个参数时默认的排序方法时从小到大排序。
sort降序排序代码:
<span style="font-size:18px;">#include<stdio.h> #include<algorithm> using namespace std; bool cmp(int a,int b) { return a>b; } int main() { int a[10]={2,5,3,0,1,5,6,2,8,4}; printf("排序前:"); for(int i=0;i<10;i++) printf("%d ",a[i]); sort(a,a+10,cmp); printf(" "); printf("排序后:"); for(int i=0;i<10;i++) printf("%d ",a[i]); printf(" "); return 0; }</span>
当然,如果不想写函数,C++标准库的强大功能完全可以解决这个问题。
less<数据类型>() //升序排序
greater<数据类型>() //降序排序
例如:sort(a,a+10,less<int>());
sort(a,a+10,greater<int>());
sort函数也可以实现根据ASCII码值对字符进行排序,只需把数据类型改成char就可以了。
sort函数对结构体进行排序
<span style="font-size:18px;">#include<stdio.h> #include<algorithm> using namespace std; struct student { int grade; int num_id; }stu[10]; bool cmp(struct student a,struct student b) { if(a.grade!=b.grade) return a.grade>b.grade; //若成绩不相等,按成绩降序 else return a.num_id>b.num_id; //若成绩相等,按学号降序 } int main() { for(int i=0;i<10;i++) scanf("%d %d",&stu[i].grade,&stu[i].num_id); sort(stu,stu+10,cmp); printf("成绩 学号 "); for(int i=0;i<10;i++) printf("%d %d ",stu[i].grade,stu[i].num_id); return 0; }</span>
sort函数对pair数组进行排序
如果不写函数的话使用sort函数对pair数组排序,默认按first进行升序排序
当然想按其他对某个值进行排序的话就得写cmp函数了
在格式上跟上面的并没有很大的区别
注意参数的写法就可以了
例如:
typedef pair<int,int> P;
bool cmp(const P &a, const P &b) //P为pair数组 { if (a.first < b.first) return true; else return false; }</span>
sort函数对字符数组进行排序
杭电1862 EXCEL排序 http://acm.hdu.edu.cn/showproblem.php?pid=1862
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; struct student { char stuID[10]; char name[10]; int grade; }stu[100005]; bool cmp1(struct student a,struct student b) { return strcmp(a.stuID,b.stuID)<0; } bool cmp2(struct student a,struct student b) { if(strcmp(a.name,b.name)==0) return strcmp(a.stuID,b.stuID)<0; else return strcmp(a.name,b.name)<0; } bool cmp3(struct student a,struct student b) { if(a.grade==b.grade) return strcmp(a.stuID,b.stuID)<0; else return a.grade<b.grade; } int main() { int i,n,c,k=0; while(scanf("%d %d",&n,&c),n,c) { for(i=0;i<n;i++) scanf("%s %s %d",&stu[i].stuID,stu[i].name,&stu[i].grade); if(c==1) sort(stu,stu+n,cmp1); else if(c==2) sort(stu,stu+n,cmp2); else if(c==3) sort(stu,stu+n,cmp3); printf("Case %d: ",++k); for(i=0;i<n;i++) printf("%s %s %d ",stu[i].stuID,stu[i].name,stu[i].grade); } return 0; }
对于cmp函数的写法没有什么固定的模板,需要根据实际情况灵活多变的去写
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: C++sort 函数用法
- 下一篇: C++之STL中sort函数的内部实现(二)