【算法】排序使用STL库中的sort算法(C++源码)
- 一、设计
- 二、要求:
- 三、设计思路
- 四、源代码(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;
}
}
}