网站维护做啥的,手机网站可以做百度商桥吗,二级域名备案,网站的站点地图设计文章目录 sort()排序函数#xff08;c#xff09;一、原理二、使用方法#xff08;一#xff09;头文件#xff08;二#xff09;使用语法1.方式一#xff08;默认#xff09;2.方式二#xff1a;定义升序或降序3.方式三#xff1a;自定义 sort()排序函数#xff08… 文章目录 sort()排序函数c一、原理二、使用方法一头文件二使用语法1.方式一默认2.方式二定义升序或降序3.方式三自定义 sort()排序函数c
一、原理
STL中的sort()并非只是普通的排序除了对普通的快速排序进行优化它还结合了插入排序和堆排序。根据不同的数量级别以及不同的情况能自动选用合适的排序方法。
二、使用方法
一头文件
#includealgorithmalgorithm意为算法是c的标准模板库STL中最重要的头文件之一提供了大量基于迭代器的非成员模板函数
二使用语法
1.方式一默认
void sort (RandomAccessIterator first, RandomAccessIterator last);first:起始位置last:末位置
两个参数first,last将[first, last) 区间内元素升序从小到大排列。【注意区间为左闭右开】
例
对数组进行排序
#includebits/stdc.h
using namespace std;int main()
{int a[10]{5,3,1,6,7,9,4,2,8,0};sort(a,a10);for(int i0;i10;i)couta[i] ;return 0;
}对字符串进行排序
#includebits/stdc.h
using namespace std;int main()
{string akjfxnzqsad;sort(a.begin(),a.end());coutaendl;return 0;
}2.方式二定义升序或降序
void sort (RandomAccessIterator first, RandomAccessIterator last, greatertype()或lesstype());greater():从大到小排序less():从小到大排序type表示数据类型如果数据类型为整形即函数为greaterint()其他数据类型如float、double等同理但不支持string数据类型
例对字符串进行降序
#includebits/stdc.h
using namespace std;int main()
{string akjfxnzqsad;sort(a.begin(),a.end(),greaterchar());coutaendl;return 0;
}在sort函数中greaterstring()不能用于string类型的排序。greater是一个函数对象通常用于比较基本数据类型如int、float等而不是用于string。
3.方式三自定义
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);自定义排序: 需用户指定排序规则Compare comp,将 [first, last)区间内的元素按照用户指定的顺序排列。
使用sort()我们不仅仅可以从大到小或者从小到大排序还可以按照一定的准则进行排序
例
使用自定义的形式对数组进行降序
#includebits/stdc.h
using namespace std;bool cmp(int x,int y)
{return xy;
}int main()
{int a[10]{2,9,6,3,5,8,7,4,1,0};sort(a,a10,cmp);for(int i0;i10;i)couta[i] ;return 0;
}根据个位数大小对数字进行排序
#includebits/stdc.h
using namespace std;bool cmp(int x,int y)
{return x%10y%10;
}int main()
{int a[10]{56,988,633,31,52,84,79,45,117,0};sort(a,a10,cmp);for(int i0;i10;i)couta[i] ;return 0;
}对结构体进行排序
对结构体进行排序时必须使用自定义函数
#includeiostream
#includestring
#includealgorithm
using namespace std;struct Student{string name;int score;
};bool cmp_score(Student x,Student y){return x.score y.score;
}int main(){Student stu[3];string n;int s;for(int i0;i3;i){cinstu[i].namestu[i].score;}sort(stu,stu3,cmp_score);for(int i0;i3;i){coutstu[i].name stu[i].scoreendl;}return 0;
}