STL中的sort()并非只是普通的排序,除了对普通的快速排序进行优化,它还结合了插入排序和堆排序。根据不同的数量级别以及不同的情况,能自动选用合适的排序方法。
#include
algorithm意为算法,是c++的标准模板库(STL)中最重要的头文件之一,提供了大量基于迭代器的非成员模板函数
void sort (RandomAccessIterator first, RandomAccessIterator last);
两个参数first,last,将==[first, last) 区间内元素升序(从小到大)排列。【注意区间为左闭右开】==
例:
对数组进行排序
#include
using namespace std;
int main()
{
int a[10]={5,3,1,6,7,9,4,2,8,0};
sort(a,a+10);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
return 0;
}
对字符串进行排序
#include
using namespace std;
int main()
{
string a="kjfxnzqsad";
sort(a.begin(),a.end());
cout<<a<<endl;
return 0;
}
void sort (RandomAccessIterator first, RandomAccessIterator last, greater<type>()或less<type>());
greater()
,其他数据类型如float、double等同理,但不支持string数据类型例:对字符串进行降序
#include
using namespace std;
int main()
{
string a="kjfxnzqsad";
sort(a.begin(),a.end(),greater<char>());
cout<<a<<endl;
return 0;
}
在sort
函数中,greater
不能用于string
类型的排序。greater
是一个函数对象,通常用于比较基本数据类型(如int
、float
等),而不是用于string
。
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
自定义排序: 需用户指定排序规则Compare comp
,将 [first, last)
区间内的元素按照用户指定的顺序排列。
使用sort()我们不仅仅可以从大到小或者从小到大排序,还可以按照一定的准则进行排序
例:
使用自定义的形式对数组进行降序
#include
using namespace std;
bool cmp(int x,int y)
{
return x>y;
}
int main()
{
int a[10]={2,9,6,3,5,8,7,4,1,0};
sort(a,a+10,cmp);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
return 0;
}
根据个位数大小对数字进行排序
#include
using namespace std;
bool cmp(int x,int y)
{
return x%10>y%10;
}
int main()
{
int a[10]={56,988,633,31,52,84,79,45,117,0};
sort(a,a+10,cmp);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
return 0;
}
对结构体进行排序
对结构体进行排序时必须使用自定义函数
#include
#include
#include
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 i=0;i<3;i++){
cin>>stu[i].name>>stu[i].score;
}
sort(stu,stu+3,cmp_score);
for(int i=0;i<3;i++){
cout<<stu[i].name<<" "<<stu[i].score<<endl;
}
return 0;
}