070.结构体-结构体案例2

#include <iostream>
using namespace std;

struct Hero
{
    //姓名
    string name;
    //年龄
    int age;
    //性别
    string sex;
};

//冒泡排序实习年龄升序排列
void bubblesort(Hero heroarry[], int len)
{
    for (size_t i = 0; i < len - 1; i++)
    {
        for (size_t j = 0; j < len - i - 1; j++)
        {
            if (heroarry[j].age > heroarry[j + 1].age)
            {
                struct     Hero temp = heroarry[j];
                heroarry[j] = heroarry[j + 1];
                heroarry[j + 1] = temp;
            }
        }
    }
}
void printhero(Hero heroarray[], int len)
{
    for (size_t i = 0; i < len; i++)
    {
        cout << "姓名:" << heroarray[i].name << " 年龄:" << heroarray[i].age << "  性别:" << heroarray[i].sex << endl;
    }
}

int main()
{
    //1.设计英雄结构体

    //2.创建数组存放5名英雄
    Hero heroarray[5] =
    {
        {"刘备",23,""},
        {"关羽",22,""},
        {"张飞",20,""},
        {"赵云",21,""},
        {"貂蝉",19,""},
    };
    cout << "排序前" << endl;
    int len = sizeof(heroarray) / sizeof(heroarray[0]);
    for (size_t i = 0; i < len; i++)
    {
        cout << "姓名:" << heroarray[i].name << " 年龄:" << heroarray[i].age << "  性别:" << heroarray[i].sex << endl;
    }


    //3.对数组进行排序,按照年龄进行升序排序
    bubblesort(heroarray, len);

    //4.将排序后的结果打印输出
    cout << "排序后" << endl;
    printhero(heroarray, len);

    system("pause");
    return 0;
}

 

posted @ 2021-09-04 18:28  梦之心  阅读(33)  评论(0编辑  收藏  举报