【算法】排序使用STL库中的sort算法(C++源码)

【算法】排序使用STL库中的sort算法(C++源码)

一、设计

请设计包含身高、学生性别信息的学生结构体,随机生成n(n>10)个学生根据学生的身高按降序进行排序并打印输出(排序可以使用STL库中的sort算法);

二、要求:

1、学生的身高,男生取值范围在160cm-180cm之间,女生在150- 170cm之间(提示:rand()%21可以生成0-20之间的整数);
2、学生的性别为字符串:男生对应字符“male”,女生对应字 符”female”(提示:可以随机生成0-1整数,如果当前值为0,可 以将学生性别设为“male”,反之则设为“female”)。

三、设计思路

① 定义结构体包含身高和存储性别的flag;
② 使用rand()函数随机生成1或0,分别代表女或男,再用rand()函数随机生成男女身高;
③ 编写cmp()函数进行男女排序,身高排序;
④ 输出

四、源代码(C++)

#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<ctime>

using namespace std;

struct students
{
    int high; 
	int flag; 
}stu[100];

bool cmp(students a,students b)
{
	if(a.high==b.high)
	{
		return a.flag>b.flag;
	}
	return a.high>b.high;
}

int main()
{
	srand(time(NULL));

	int n;
	int i;

	cout<<"Please enter the number of students:";

	cin>>n;

	for(i=0;i<n;i++)
	{
		stu[i].flag=rand()%2;//随机生成0-1
		if(stu[i].flag==0)
		{
			//male
			stu[i].high=rand()%21+160;
		}
		else
		{
			//female
			stu[i].high=rand()%21+150;
		}
	}

	for(i=0;i<n;i++)
	{
		if(stu[i].flag==0)
		{
			cout<<stu[i].high<<",";
			cout<<"male"<<endl;
		}
		else
		{
			cout<<stu[i].high<<",";
			cout<<"female"<<endl;
		}
	}

	sort(stu,stu+n,cmp);

	cout<<"After sorting:"<<endl;

	for(i=0;i<n;i++)
	{
		if(stu[i].flag==0)
		{
			cout<<stu[i].high<<",";
			cout<<"male"<<endl;
		}
		else
		{
			cout<<stu[i].high<<",";
			cout<<"female"<<endl;
		}
	}
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码两年半的练习生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值