sort函数

1.基本形式

C++的sort函数主要用于对元素序列进行排序,默认情况下是按照升序排序。

sort函数的最基本形式是:

void sort(RandomAccessIterator first, RandomAccessIterator last);
  • first:序列中要排序的第一个元素的迭代器

  • last:序列中最后一个元素之后的迭代器(即序列的结束)。

sort 还有一个重载版本,允许你指定一个自定义比较函数或比较对象,以定义排序的准则:

void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
  • comp:一个比较函数,它接受两个元素作为参数,如果第一个元素应该排在第二个元素之前,则返回 true。这允许进行自定义排序,例如降序排序或根据对象的某个特定属性进行排序。

2.如何实现比较函数cmp

        下面介绍对于基本数据类型、结构体类型、STL容器进行自定义排序cmp的写法。

        2.1基本数据类型数组的排序

若比较函数不填,默认升序排序 ,下面为对int数组的排序:

#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
	int a[5] = {3,5,2,1,4};
	sort(a,a+5);
	for(int i=0;i<5;i++){
		printf("%d",a[i]);
	}
	return 0;
}


  输出结果:

12345
 如果想要降序排列,则需要使用cmp函数“告诉”sort何时交换元素,可以这样写:

#include <stdio.h>
#include <algorithm>
using namespace std;
bool cmp(int a,int b){
	return a>b;
	//可以理解为a>b时,把a放在前面 
}
int main(){
	int a[5] = {3,5,2,1,4};
	sort(a,a+5,cmp);
	for(int i=0;i<5;i++){
		printf("%d",a[i]);
	}
	return 0;
}


  输出结果:

54321
        这样就可以让数值大的元素在前面,即降序排列,对于double,char亦如此,把cmp内传入参数的类型改变一下就好了。

2.2结构体数组的排序

按x从大到小排序

#include <stdio.h>
#include <algorithm>
using namespace std;
struct node{
    int x,y;
}ssd[10];
bool cmp(node a, node b){
    return a.x > b.x; //按照x降序排列 
}
int main(){
	ssd[0].x=2; //{2,2} 
	ssd[0].y=2;
	ssd[1].x=1; //{1,3}
	ssd[1].y=3;
	ssd[2].x=3; //{3,1}
	ssd[2].y=1;
	sort(ssd,ssd+3,cmp);
	for(int i=0;i<3;i++){
		printf("%d %d\n",ssd[i].x,ssd[i].y);
	}
	return 0;
}

输出:

3 1
2 2
1 3

如果想先按照x降序,x相等时,y升序排列(二级排序),那么:

#include <stdio.h>
#include <algorithm>
using namespace std;
struct node{
    int x,y;
}ssd[10];
bool cmp(node a, node b){
    if(a.x!=b.x) return a.x>b.x;
	else return a.y < b.y; //按照x降序排列 
}
int main(){
	ssd[0].x=2; //{2,2} 
	ssd[0].y=2;
	ssd[1].x=1; //{1,3}
	ssd[1].y=3;
	ssd[2].x=2; //{2,1}
	ssd[2].y=1;
	sort(ssd,ssd+3,cmp);
	for(int i=0;i<3;i++){
		printf("%d %d\n",ssd[i].x,ssd[i].y);
	}
	return 0;
}

输出:

2 1
2 2
1 3

2.3容器的排序

在STL标准容器中,只有vector、string、deque可以使用sort。这是因为像set,map这种容器是用红黑树实现的,元素本身有序,因此不允许使用sort排序。

#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(int a,int b){
	return a>b;
}
 
int main(){
	vector<int> vi;
	vi.push_back(3);
	vi.push_back(1);
	vi.push_back(2);
	sort(vi.begin(),vi.end(),cmp); //整个排序
	for(int i=0;i<3;i++){
		printf("%d ",vi[i]);
	} 
	return 0;
}

结合lambda函数,我们可以直接在函数体内定义自定义函数。

# include <bits/stdc++.h>
using namespace std;

int main(){
    vector<int>a{4, 1, 3, 5, 2};
    // 使用自定义比较函数排序
    sort(a.begin(),a.end(),[](int &a,int &b){
        return a > b;
         });
    for(int x:a){
        cout<<x<<" ";
    }
    // 输出5 4 3 2 1
}

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值