案例描述

设计一个英雄的结构体,包括成员的年龄,性别,姓名;创建结构体数组,数组中存放5名英雄。
通过冒泡排序的算法,将数组中的英雄按照年龄进行升序排序,最后将结果打印

代码实现

  1. #include <iostream>
  2. using namespace std;
  3. //1,设计英雄结构体
  4. struct Hero{
  5. string Name;
  6. int age;
  7. string sex;
  8. };
  9. //打印函数
  10. void heroprint(struct Hero heroArray[],int len)
  11. {
  12. //cout<<"asasda"<<endl;
  13. for(int i=0;i<len;i++)
  14. {
  15. cout<<"姓名:"<<heroArray[i].Name
  16. <<"\t年龄: "<<heroArray[i].age
  17. <<"\t性别:"<<heroArray[i].sex<<endl;
  18. }
  19. }
  20. //冒泡排序
  21. void herosort(struct Hero heroArray[],int len)
  22. {
  23. for(int i=0;i<len-1;i++)
  24. {
  25. for(int j=0;j<len-i-1;j++)
  26. {
  27. if(heroArray[j].age<heroArray[j+1].age)
  28. {
  29. struct Hero temp = heroArray[j];
  30. heroArray[j] = heroArray[j+1];
  31. heroArray[j+1] = temp;
  32. }
  33. }
  34. }
  35. }
  36. int main()
  37. {
  38. //2,设计数组存放5名英雄
  39. struct Hero heroArray[5]=
  40. {
  41. {"刘备",55,"男"},
  42. {"赵云",35,"男"},
  43. {"公孙离",25,"女"},
  44. {"白起",45,"男"},
  45. {"亚索",32,"男"},
  46. };
  47. int len = sizeof(heroArray)/sizeof(heroArray[0]);
  48. cout<<"排序前:"<<endl;
  49. heroprint(heroArray,len);
  50. //3,对数组进行排序,按照年龄进行升序排序
  51. cout<<"排序后:"<<endl;
  52. herosort(heroArray,len);
  53. heroprint(heroArray,len);
  54. //将排序后结果打印输出
  55. return 0;
  56. }