sort()函数

如何使用

sor()的使用必须加上头文件#include和using namespace std;
其使用方式如下:
sort(首元素地址(必填),尾元素下个地址(必填),比较函数(非必填));
如果不写比较函数,将默认对前面给出的区间进行递增排序
示例:

#include<iostream>
#include<algorithm>
int main()
{
	using namespace std;
	int a[5]={1,9,13,2,0};
	sort(a,a+4);
	for(int i=0;i<5;i++)
	{
		cout<<a[i]<<" ";//将对前四个元素进行递增排序
	}
} 

同理可对double型,char型(默认为字典顺序)进行排序

如何实现比较函数cmp

int,double,char

如果想要从小到大排序,可以这样定义cmp

bool cmp(int x,int y)
{
	return x>y;
}
#include<iostream>
#include<algorithm>
bool cmp(int x,int y)
{
	return x>y;
}
int main()
{
	using namespace std;
	int a[5]={1,9,13,2,0};
	sort(a,a+4,cmp);
	for(int i=0;i<5;i++)
	{
		cout<<a[i]<<" ";
	}
} 

即可实现递减排序
double,char同理,只需修改cmp的形参

结构体数组

现在定义了如下结构体

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

我们想将ssd数组按x从大到小,只需要

bool cmp(node a,node b){
	return a.x>b.x;
}

容器的排序

STL标准容器中,只有vector,string,deque可以使用

#include<iostream>
#include<algorithm>
#include<vector>
bool cmp(int x,int y)
{
	return x<y;
}
int main()
{
	using namespace std;
	vector<int> a;
	a.push_back(1);
	a.push_back(3);
	a.push_back(2);
	sort(a.begin(),a.end(),cmp);
	for(int i=0;i<3;i++)
	{
		cout<<a[i]<<" ";
	}
} 

再看string的排序(按字典序)

#include<iostream>
#include<algorithm>
#include<string>
int main()
{
	using namespace std;
	string str[3]={"bbb","aaaaa","ccc"};
	sort(str,str+3);
	for(int i=0;i<3;i++)
	{
		cout<<str[i]<<endl;
	}
} 

如果想按照字符串的长度从小到大排序,则可以这样:

#include<iostream>
#include<algorithm>
#include<string>
bool cmp(std::string str1,std::string str2)
{
	return str1.length()>str2.length();
}
int main()
{
	using namespace std;
	string str[3]={"bbb","aaaaa","ccc"};
	sort(str,str+3);
	for(int i=0;i<3;i++)
	{
		cout<<str[i]<<endl;
	}
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值