sort函数与排序

C++库中用来排序的函数

使用sort()进行排序

  • 头文件:algorithm
  • 函数原型:

template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

  • 使用:
    sort(首元素地址[必填],尾元素地址的下一个地址[必填],比较函数[非必填])
    前两个参数是必填的,如果没有比较函数,默认进行递增排序。

sort还可以对STL容器进行排序,但只能对vector,string和deque使用sort。

  • 比较函数
    bool cmp(type a1, type a2)
    { return [a1排在a2前面的条件] ; }

举例

  • 无比较函数
#include <stdio.h>
#include <algorithm>
using namespace std;

int main()
{
	int a[6] = {9,4,2,5,6,-1};
	sort(a,a+6);
	for(int i = 0; i < 6;i++)
	{
		printtf("%d ",a[i]);
	}
	return 0;
}

结果:-1 2 4 5 6 9
结果分析:由于没有定义比较函数,所以默认按照递增排序;首元素地址为数组首元素地址,即指向 9,尾元素下一地址为a+6,即指向-1的后一个元素地址。所以对9 ~ -1的这6个元素递增排序。

  • 有比较函数
#include <stdio.h>
#include <algorithm>
using namespace std;

bool cmp(int a1,int a2)
{
	return a1 > a2;
}

int main()
{
	int a[6] = {9,4,2,5,6,-1};
	sort(a,a+6,cmp);
	for(int i = 0; i < 6;i++)
	{
		printtf("%d ",a[i]);
	}
	return 0;
}

结果:9 6 5 4 2 -1
结果分析:与上一个例子不同的是增加了比较函数。观察比较函数,a1排在a2之前的条件是a1>a2,换句话说sort函数按照递减排序。所以得到如上结果。

  • 对结构体数组进行排序
#include <stdio.h>
#include <algorithm>
using namespace std;

struct s{
int x,y;
}ss[10];

bool cmp(s a1,s a2)
{
	if(a1.x != a2.x)
		return a1.x > a2.x;
	else
		return a1.y < a2.y;
}

int main()
{
	ss[0].x = 9; ss[0].y = 1; 
	ss[1].x = 4; ss[1].y = 2; 
	ss[2].x = 2; ss[2].y = 3; 
	ss[3].x = 5; ss[3].y = 4; 
	ss[4].x = 6; ss[4].y = 5; 
	ss[5].x = -1; ss[5].y = 6; 
	ss[6].x = -1; ss[5].y = 5;
	ss[7].x = 5; ss[5].y = 5;
	ss[8].x = 4; ss[5].y = -1;
	ss[9].x = 9; ss[5].y = 3;
	
	sort(ss,ss+10,cmp);

	for(int i = 0; i < 6;i++)
	{
		printf("%d %d\n",ss[i].x ,ss[i].y);
	}
	return 0;
}

结果:
9 1
9 3
6 5
5 4
5 5
4 -1
4 2
2 3
-1 5
-1 6
结果分析:在这个例子中定义了一个结构体数组ss。观察cmp函数,当a1.x != a2.x时,按x的降序排序;当 a1.x == a2.x时,按y的升序排序。

  • 容器的排序
#include <stdio.h>
#include <vector> /*包含vector和string库*/
#include <string>
#include <algorithm>
using namespace std;

int main()
{
	vector<int> v;
	v.push_back(3);
	v.push_back(2);
	v.push_back(1);
	sort(v.begin(),v.end());
	for(int i = 0; i < 3;i++)
	{	printf("%d ",v[i]); }

	printf("\n");

	string s[3] = {bb, ccc,aaaa};
	sort(s,s+3);
	for(int i = 0;i < 3;i++)
	{	printf("%s\n", s[i]); }

	return 0;
}

结果:
1 2 3
aaaa
bb
ccc
结果分析:对于vector,按照int从小到大排序;对于string,按照字典序从小到大排序。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值