#include <iostream> using namespace std; struct Student { string name; int age; string sex; }; void printStuArr(Student stuArr[]) { for (int i = 0; i < 4; i++) { cout << stuArr[i].name << "," << stuArr[i].age << "," << stuArr[i].sex << endl; } } void bubbleSort(Student stuArr[]) { for (int i = 3; i >= 0; i--) { for (int j = i - 1; j >= 0; j--) { if (stuArr[i].age < stuArr[j].age) { Student tmp = stuArr[i]; stuArr[i] = stuArr[j]; stuArr[j] = tmp; } } } } int main() { struct Student stuArr[4]; struct Student stu1 = { "liub",23,"男" }; struct Student stu2 = { "guangy",19,"男" }; struct Student stu3 = { "zhangf",25,"男" }; struct Student stu4 = { "diaoc",18,"女" }; stuArr[0] = stu1; stuArr[1] = stu2; stuArr[2] = stu3; stuArr[3] = stu4; bubbleSort(stuArr); printStuArr(stuArr); system("pause"); return 0; }
输出:
按照年龄将结构体数组中的 元素进行排序。