c++程序—结构体排序函数

#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 << "\t" << arr[i].name << "\t" << arr[i].age << "\t" << 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 << "\t" << heroArry[i].age << "\t" << heroArry[i].sex << endl;

    //}
    cout << "按照年龄排序前的顺序为:" << endl;
    printhero(heroArry, len);

    bubblesort( heroArry,len);

    cout << "按照年龄排序后的顺序为:" << endl;
    printhero(heroArry, len);


    system("pause");
    return 0;

}

 

posted @ 2020-03-11 23:55  Jackie_Wang  阅读(881)  评论(0编辑  收藏  举报