美文网首页
C++结构体案例2

C++结构体案例2

作者: FredricZhu | 来源:发表于2020-11-24 14:25 被阅读0次

    对英雄数组按年龄进行排序

    #include <iostream>
    #include <string>
    using namespace std;
    
    // Hero 英雄结构体
    struct Hero
    {
        std::string name;
        int age;
        std::string sex;
    };
    
    // sortHeroes 对英雄进行冒泡排序的函数
    void sortHeroes(struct Hero hero[], int len)
    {
        for (int i = 0; i < len; i++)
        {
            for (int j = 0; j < len - i - 1; j++)
            {
                if (hero[j].age > hero[j + 1].age)
                {
                    struct Hero tmp = hero[j];
                    hero[j] = hero[j + 1];
                    hero[j + 1] = tmp;
                }
            }
        }
    }
    
    void sortHeroesByPtr(struct Hero *hero, int len)
    {
        for (int i = 0; i < len; i++)
        {
            // 进行一轮比较前,先要把头指针保留
            struct Hero *head = hero;
            for (int j = 0; j < len - i - 1; j++)
            {
                struct Hero *cur = head;
                struct Hero *next = ++head;
                // 注意是交换值,不是交换地址
                if (cur->age > next->age)
                {
                    struct Hero tmp = *cur;
                    *cur = *next;
                    *next = tmp;
                }
            }
        }
    }
    
    // printHeroes 打印英雄信息的函数
    void printHeroes(struct Hero *hero, int len)
    {
        for (int i = 0; i < len; i++)
        {
            std::cout << "英雄名字: " << hero->name << "英雄年龄: " << hero->age
                      << "英雄性别: " << hero->sex << std::endl;
            hero++;
        }
    }
    
    int main()
    {
        struct Hero hArray[5] = {
            {"刘备", 23, "男"},
            {"关羽", 22, "男"},
            {"张飞", 20, "男"},
            {"赵云", 21, "男"},
            {"貂蝉", 19, "女"}};
    
        int len = sizeof(hArray) / sizeof(hArray[0]);
        std::cout << "排序前的hero数组" << std::endl;
        printHeroes(hArray, len);
    
        sortHeroesByPtr(hArray, len);
    
        std::cout << "排序后的hero数组" << std::endl;
        printHeroes(hArray, len);
        getchar();
        return 0;
    }
    

    输出结果


    图片.png

    相关文章

      网友评论

          本文标题:C++结构体案例2

          本文链接:https://www.haomeiwen.com/subject/pfviiktx.html