sort函数

STL中的sort函数包含于文件”algorithm“中,sort有两个重载函数,因此有两种调用方式:sort(begin, end)和sort(begin, end, compare),默认的排序结果是从小到大。

1. 对于基本数据类型我们可以直接使用第一种调用方式

#include <algorithm>
#include <iostream>
using namespace std;

int main()
{

	int ar[10];
	for (int i=0; i<10; ++i)
	{
		ar[i] = 10 - i;
	}
	cout<<"原序列:";
	for (int i=0; i<10; ++i)
	{
		cout<<ar[i]<<" ";
	}
	cout<<endl;

	sort(ar, ar+10);
	for (int i=0; i<10; ++i)
	{
		cout<<ar[i]<<" ";
	}

	return 1;
}

2. 当我们想要的排序结果是从达到小时需要定义比较函数

#include <algorithm>
#include <iostream>
using namespace std;

bool comp(int a, int b)
{
	return a>b;
};


int main()
{

	int ar[10];
	for (int i=0; i<10; ++i)
	{
		ar[i] = i;
	}
	cout<<"原序列:";
	for (int i=0; i<10; ++i)
	{
		cout<<ar[i]<<" ";
	}
	cout<<endl;

	sort(ar, ar+10, comp);
	for (int i=0; i<10; ++i)
	{
		cout<<ar[i]<<" ";
	}

	return 1;
}

3. 对于复杂的数据结构我们有两种处理策略

3.1 类似2中所示定义比较函数

例子略

3.2 在数据结构中定义比较函数

#include <algorithm>
#include <iostream>
using namespace std;

struct node
{
	int a;
	int b;
	bool operator<(struct node n1)
	{
		return b < n1.b;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	struct node *no = new struct node[10];
	for (int i=0; i<10; ++i)
	{
		no[i].a = i;
		no[i].b = 10 - i;
	}
	for (int i=0; i<10; ++i)
	{
		cout<<no[i].a<<" "<<no[i].b<<endl;
	}
	cout<<"///"<<endl;
	sort(no, no+10);
	for (int i=0; i<10; ++i)
	{
		cout<<no[i].a<<" "<<no[i].b<<endl;
	}
	return 0;
}

同样道理将struct node中的return  b  < n1.b 改为  return  b  > n1.b排序结果将是从大到小。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值