sort()使用需要头文件<algorithm>
和using namespace std;
函数名 | 功能描述 |
---|---|
sort | 对给定区间所有元素进行排序 |
stable_sort | 对给定区间所有元素进行稳定排序 |
partial_sort | 对给定区间所有元素进行部分排序 |
partial_sort_copy | 对给定区间复制并排序 |
nth_element | 找出给定区间的某个位置对应的元素 |
is_sorted | 判断一个区间是否已经排好序 |
partition | 使得符合某个条件的元素放在前面 |
stable_partition | 相对稳定的 使得符合某个条件的元素放在前面 |
语法:sort(begin, end, cmp)
,其中begin
为指向待sort()
的数组的第一个元素的指针,end
为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp
参数为排序准则,如果没有的话,默认以非降序排序。
以int为例的基本数据类型sort()使用
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[5] = {1, 3, 4, 2, 5};
sort(a, a + 5);
for (int i = 0; i < 5; i++) cout << a[i] << ' ';
return 0;
}
输出结果为:1 2 3 4 5
自定义cmp参数
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int x, int y) {
return x > y;
}
int main() {
int a[5] = {1, 3, 4, 2, 5};
sort(a, a + 5, cmp);
for (int i = 0; i < 5; i++) cout << a[i] << ' ';
return 0;
}
输出结果为:5 4 3 2 1
相对于C语言内置的qsort函数,C++中提供的sort函数使用起来更方便,不需要做指针类型转换,qsort函数使用起来比较麻烦,涉及到很多指针的操作。
sort有两种用法:第一种是传入一个functor对象,另一种是直接传入一个排序函数,使用functor比直接使用函数快。但实践表明,传入functor对象还是没有qsort函数快,但在有的平台下又有不同。
下面是测试代码:
#include <stdio.h>
#include <time.h>
#include <algorithm>
using namespace std;
#define _for(i,a,b) for(int i=(a);i<(b);++i)
const int N=10000000;
struct TS{
int a,b,c;
};
inline bool cmp(const TS& t1,const TS& t2){
if(t1.a!=t2.a) return t1.a<t2.a;
if(t1.b!=t2.b) return t1.b<t2.b;
return t1.c<=t2.c;
}
int cmp4qsort(const void *a,const void *b){
TS *t1=(TS*)a,*t2=(TS*)b;
if(t1->a != t2->a) return t1->a - t2->a;
if(t1->b != t2->b) return t1->b - t2->b;
return t1->c - t2->c;
}
struct cmpFunctor{
inline bool operator() (const TS& t1,const TS& t2){
if(t1.a!=t2.a) return t1.a<t2.a;
if(t1.b!=t2.b) return t1.b<t2.b;
return t1.c<=t2.c;
}
};
TS tss[N];
void genData(){
_for(i,0,N){
tss[i].a=rand();
tss[i].b=rand();
tss[i].c=rand();
}
}
int main(){
srand(time(NULL));
genData();
clock_t start=clock();
sort(tss,tss+N,cmp);
printf("sort by function pointer : %ld\n",clock() - start);
genData();
start=clock();
sort(tss,tss+N,cmpFunctor());
printf("sort by functor : %ld\n",clock() - start);
genData();
start=clock();
qsort(tss,N,sizeof(TS),cmp4qsort);
printf("qsort by function pointer : %ld\n",clock() - start);
return 0;
}
/*
sort by function pointer : 3127
sort by functor : 3008
qsort by function pointer : 2510
*/