sort()

sort()

如何使用sort函数

头文件:include <iostream>以及using namespace std;

sort(首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(选填))

对尾元素下一个地址的理解:也可以是从首元素地址开始,给几个数进行排序,就第二个参数加几

如果不写比较函数则默认对前面给出的区间进行递增排序

示例:

#include <iostream>
#include<algorithm>
using namespace std;
int main(){
	int a[6]={2,3,1,7,9,5};
	sort(a,a+4);
	for(int i=0;i<6;i++){
		cout<<a[i]<<" ";
	}
	cout<<endl;
	sort(a,a+6);
	for(int i=0;i<6;i++){
		cout<<a[i]<<" ";
	}
	cout<<endl;
} 

对char进行排序是默认按字典序

如果没有可比性,则需要人为制定比较规则,sort函数中第三个参数就是用来制定规则的

如何实现比较函数cmp

基本数据类型数组的排序

如果要从大到小排序,则用cmp函数告诉sort(),何时要交换元素(让大小比较关系反过来),是一个bool类型的函数

bool cmp(int a,int b){
	return a>b;	//当a大于b时,a放在前面
}

结构体数组的排序

定义一个结构体

struct node{
	int x,y;
}ssd[10];

一级排序:按x从大到小进行排序

bool cmp(node a,node b){
	return a.x>b.x;			//按照x从大到小排序 
}

二级排序:当x相等的情况下,按照y的大小从小到大进行排序

bool cmp(node a,node b){
    if(a.x!=b.x) return a.x>b.x;
    else return a.y<b.y;
}

测试程序:

#include <iostream>
#include <algorithm>
using namespace std;
struct node{
	int x,y;
}ssd[10];
bool cmp1(node a,node b){
	return a.x>b.x;			//按照x从大到小排序 
}
bool cmp2(node a,node b){
    if(a.x!=b.x) return a.x>b.x;
    else return a.y<b.y;
}
int main(){
	ssd[0].x=2;
	ssd[0].y=2;
	ssd[1].x=1;
	ssd[1].y=3;
	ssd[2].x=3;
	ssd[2].y=1;
	ssd[3].x=1;
	ssd[3].y=2;
	sort(ssd,ssd+3,cmp1);
	for(int i=0;i<3;i++){
		cout<<ssd[i].x<<" "<<ssd[i].y<<endl;
	}
	sort(ssd,ssd+4,cmp2);
	for(int i=0;i<4;i++){
		cout<<ssd[i].x<<" "<<ssd[i].y<<endl;
	}
	return 0;
}

输出:

3 1
2 2
1 3
3 1
2 2
1 2
1 3

容器排序

在STL标准容器中,只有vector,string,deque可以用排序

vector:

#include <iostream>
#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++){
		cout<<vi[i];
	}
	return 0;
}

输出

321

string:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(string str1,string str2){
	return str1.length()<str2.length();
}
int main(){
	string str[3]={"babb","bc","aaa"};
	sort(str,str+3);	//按字典序从小到大排序(一个一个字母比) 
	for(int i=0;i<3;i++){
		cout<<str[i]<<endl;
	}
	sort(str,str+3,cmp);		//按字符串长度排序 
	for(int i=0;i<3;i++){
		cout<<str[i]<<endl;
	}
	return 0;
}

输出:

aaa
babb
bc
bc
aaa
babb
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值