C++的sort函数是一很方便的排序方法,如果你经常使用低效的选择和冒泡排序,其他的什么快速排序,归并排序等等又懒的使用。那么这个可以sort再适合你不过了。而且sort函数是类似于快速排序的方法,效率很高,时间复杂度为O(n)=nlog2(n)。原理是什么这里不说,先告诉你怎么用。
sort函数的头文件在#include<algorithm>的C++标准库中。
sort函数有3个参数:第一个参数是待排序数据的首地址;第二个参数是待排序数据的结束地址;第三个参数是排序规则,也就是小→大/大→小,可以省略,如果省略,则默认为小→大。
例子:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int num[10]={2,4,6,8,10,1,3,5,7,9};
int i;
sort(num,num+10); //第三个参数省略,默认小→大
for(i=0;i<10;i++)
{
cout<<num[i]<<" ";
}
cout<<endl;
return 0;
}
/*
输出:
1 2 3 4 5 6 7 8 9 10
Press any key to continue
*/
第三个参数是表示排序规则,形式为sort(首地址,结束地址,complare);那么complare()是什么,complare是这样用的,例如bool complare(int a,int b){ return a>b; },这样就代表了sort函数的规则是从大→小排序。注意的是,complare是作为sort的第三个参数,直接写函数名complare就行了。
例子:
#include<iostream>
#include<algorithm>
using namespace std;
bool complare(int a,int b)
{
return a>b;
}
int main()
{
int num[10]={2,4,6,8,10,1,3,5,7,9};
int i;
sort(num,num+10,complare);
for(i=0;i<10;i++)
{
cout<<num[i]<<" ";
}
cout<<endl;
return 0;
}
/*
输出:
10 9 8 7 6 5 4 3 2 1
Press any key to continue
*/
但是每次定义排序规则(第三个参数),都要定义complare有点似乎有点麻烦,那么对于第三个参数有一个简化的使用:less<数据类型>()表示从小→大排序,greater<数据类型>()表示从大→小排序,但要包含#include<functional>头文件具体怎么使用,看例子。
例子:
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
int main()
{
int num[10]={2,4,6,8,10,1,3,5,7,9};
int i;
sort(num,num+10,greater<int>()); //第三个参数:大→小
for(i=0;i<10;i++)
{
cout<<num[i]<<" ";
}
cout<<endl;
return 0;
}
/*
输出:
10 9 8 7 6 5 4 3 2 1
Press any key to continue
*/
sort函数不单单只能对int型数据排序,对字符串也可以排序。
例子:
#include<iostream>
#include<algorithm>
#include<functional> //别忘了头文件
using namespace std;
int main()
{
char str[20]="I LOVE C++";
int i;
sort(str,str+20,greater<char>());
for(i=0;i<10;i++)
{
cout<<str[i]<<" ";
}
cout<<endl;
return 0;
}
/*
输出:
V O L I E C + +
Press any key to continue
*/
以上就是对sort函数的简单介绍,在做ACM题时,可以方便的使用,谢谢。