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

輸出:

 

按照年齡將結構體數組中的 元素進行排序。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM