案例描述
设计一个英雄的结构体,包括成员的年龄,性别,姓名;创建结构体数组,数组中存放5名英雄。
通过冒泡排序的算法,将数组中的英雄按照年龄进行升序排序,最后将结果打印
代码实现
#include <iostream>using namespace std;//1,设计英雄结构体struct Hero{string Name;int age;string sex;};//打印函数void heroprint(struct Hero heroArray[],int len){//cout<<"asasda"<<endl;for(int i=0;i<len;i++){cout<<"姓名:"<<heroArray[i].Name<<"\t年龄: "<<heroArray[i].age<<"\t性别:"<<heroArray[i].sex<<endl;}}//冒泡排序void herosort(struct Hero heroArray[],int len){for(int i=0;i<len-1;i++){for(int j=0;j<len-i-1;j++){if(heroArray[j].age<heroArray[j+1].age){struct Hero temp = heroArray[j];heroArray[j] = heroArray[j+1];heroArray[j+1] = temp;}}}}int main(){//2,设计数组存放5名英雄struct Hero heroArray[5]={{"刘备",55,"男"},{"赵云",35,"男"},{"公孙离",25,"女"},{"白起",45,"男"},{"亚索",32,"男"},};int len = sizeof(heroArray)/sizeof(heroArray[0]);cout<<"排序前:"<<endl;heroprint(heroArray,len);//3,对数组进行排序,按照年龄进行升序排序cout<<"排序后:"<<endl;herosort(heroArray,len);heroprint(heroArray,len);//将排序后结果打印输出return 0;}
