c++结构体实例之按结构体中指定变量进行排序

#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;
}

输出:

按照年龄将结构体数组中的 元素进行排序。

猜你喜欢

转载自www.cnblogs.com/xiximayou/p/12083269.html
今日推荐