C++算法:sort()函数

介绍:

        sort()函数主要是用于实现快速的排序的算法,其主要是由三部分组成,它有三个参数sort(begin,end,cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个指针,cmp参数为排序准则,cmp参数可以不写,如果不写的话,默认从小到大进行排序。

注意:

        ①sort()函数必须包含在头文件#include<algorithm>文件里

对结构体进行排序:

        在使用sort()对结构体进行排序的时候,begin和end均为结构体数组整体,再利用自定义排序规则cmp进行排序。

        我们使用一个月饼的例子进行解释说明,在本例中含有N种月饼,每个月饼有自己的价格和库存,我们按照价格的大小进行,从小到大进行排序。

结构体定义:
//设置月饼种类的结构体
struct yuebing
{
	int inventory;    //库存量
	int price;     //单个月饼的价格
}A[MAX];
cmp:
//排序规则1:按照价格从小到大排序
bool cmp_min_to_max(yuebing x , yuebing y)
{
	return x.price < y.price;
}
//排序规则2:按照价格从大到小排序
bool cmp_max_to_min(yuebing x , yuebing y)
{
	return x.price > y.price;
}
 sort()函数:
//排序1:按照从小到大排序
	sort(A,A+N,cmp_min_to_max);  

//排序2:按照从大到小排序
	sort(A,A+N,cmp_max_to_min); 
全部代码:
//sort()函数用法
#include<iostream>
#include<algorithm>
#define MAX 1000
using namespace std;

//设置月饼种类的结构体
struct yuebing
{
	int inventory;    //库存量
	int price;     //单个月饼的价格
}A[MAX];

//排序规则1:按照价格从小到大排序
bool cmp_min_to_max(yuebing x , yuebing y)
{
	return x.price < y.price;
}
//排序规则2:按照价格从大到小排序
bool cmp_max_to_min(yuebing x , yuebing y)
{
	return x.price > y.price;
}

int main()
{
	int N;    //记录数组的个数
	cout<<"请输入月饼的种类数:"<<endl;
	cin>>N;
	//输入数据
	cout<<"请输入各个月饼的库存:"<<endl;
	for(int i=0;i<N;i++)
	{
		cin>>A[i].inventory;
	}
	cout<<"请输入各个月饼的价格:"<<endl;
	for(int i=0;i<N;i++)
	{
		cin>>A[i].price;   
	}

	//输出排序前的数据
	cout<<"排序前的数据:"<<endl;
	for(int i=0;i<N;i++)
	{
		cout<<A[i].inventory<<'\t';
	}
	cout<<endl;
	for(int i=0;i<N;i++)
	{
		cout<<A[i].price<<'\t';
	}
	cout<<endl;

	//排序1:按照从小到大排序
	sort(A,A+N,cmp_min_to_max);   

	//输出从小到大排序后的数据
	cout<<"从小到大排序后的数据:"<<endl;
	for(int i=0;i<N;i++)
	{
		cout<<A[i].inventory<<'\t';
	}
	cout<<endl;
	for(int i=0;i<N;i++)
	{
		cout<<A[i].price<<'\t';
	}
	cout<<endl;

	//排序2:按照从大到小排序
	sort(A,A+N,cmp_max_to_min); 

	//输出从大到小排序后的数据
	cout<<"从大到小排序后的数据:"<<endl;
	for(int i=0;i<N;i++)
	{
		cout<<A[i].inventory<<'\t';
	}
	cout<<endl;
	for(int i=0;i<N;i++)
	{
		cout<<A[i].price<<'\t';
	}
	cout<<endl;

	system("pause");
	return 0;
}
 输出:

参考:C++ sort()排序详解-CSDN博客

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值