#include<iostream> using namespace std; #include<string> //结构体数组 struct hero { string name; int age; string sex; }; void bubblesort(hero arr[],int len) { for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - i - 1; j++) { if (arr[j]. age > arr[j+1].age) { struct hero temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } void printhero(hero arr[],int len) { for (int i = 0; i < len; i++) { cout << " " << arr[i].name << " " << arr[i].age << " " << arr[i].sex << endl; } } int main() { hero heroArry[5] = { {"刘备",23,"男"}, {"关羽",18,"男"}, {"张飞",20,"男"}, {"赵云",16,"男"}, {"黄月英",19,"女"} }; //输出结构体数组 int len = sizeof(heroArry) / sizeof(heroArry[0]); //for (int i = 0; i < len; i++) { // cout << heroArry[i].name << " " << heroArry[i].age << " " << heroArry[i].sex << endl; //} cout << "按照年龄排序前的顺序为:" << endl; printhero(heroArry, len); bubblesort( heroArry,len); cout << "按照年龄排序后的顺序为:" << endl; printhero(heroArry, len); system("pause"); return 0; }