C++ 结构体案例2 升序打印数组中的元素
1 //结构体案例 2 2 #include<iostream> 3 #include<string> 4 #include<ctime> 5 using namespace std; 6 7 struct Hero 8 { 9 string name; 10 int age; 11 string sex; 12 }; 13 14 void bubbleSort(struct Hero heroArray[] ,int len ) 15 16 { 17 for (int i = 0; i < len - 1; i++) 18 { 19 for (int j = 0; j < len - 1 - i; j++) 20 { 21 if (heroArray[j].age > heroArray[j+1].age) 22 { 23 struct Hero temp = heroArray[j]; 24 heroArray[j] = heroArray[j + 1]; 25 heroArray[j + 1] = temp; 26 27 28 29 } 30 } 31 } 32 33 } 34 void printfHero(struct Hero heroArray[],int len) 35 { 36 for (int i = 0; i < len; i++) 37 { 38 cout << "姓名: " << heroArray[i].name << " 年龄:" 39 << heroArray[i].age << heroArray[i].sex << endl; 40 41 } 42 } 43 44 int main() 45 { 46 47 //英雄的结构体 48 49 struct Hero heroArray[5] = 50 { 51 {"刘备",25,"男"}, 52 {"关于",29,"男"}, 53 {"张飞",86,"男"}, 54 {"貂蝉",12,"女"}, 55 {"赵云",32,"男"} 56 57 }; 58 int len = sizeof(heroArray) / sizeof(heroArray[0]); 59 for (int i = 0; i < len; i++) 60 { 61 cout << "姓名: " << heroArray[i].name << " 年龄:" 62 << heroArray[i].age << heroArray[i].sex << endl; 63 } 64 65 //创建数组存放5名英雄 66 67 68 //排序 69 bubbleSort(heroArray, len); 70 71 cout << "排序后的:" << endl; 72 //打印 73 printfHero(heroArray, len); 74 75 76 }
本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15098008.html