C++排序sort()

本文介绍了C++中的sort()函数,讲解了如何对基本数据类型如int进行排序,以及如何自定义cmp参数进行排序。通过示例展示了sort()函数的使用,并对比了sort()与C语言中的qsort()函数的便捷性和性能差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值