美文网首页
5.结构体案例2

5.结构体案例2

作者: lxr_ | 来源:发表于2021-01-05 17:26 被阅读0次

    #include<iostream>

    #include<string>

    #include<ctime>

    using namespace std;

    struct hero

    {

        string hName;

        int age;

    };

    void creatValue(hero h[],int len)//初始化结构体数组

    {

        string NameSeed = "abcde";

        for (int i = 0; i < len; i++)

        {

            h[i].hName = "hero_";

            h[i].hName+=NameSeed[i];

            h[i].age = rand() % 21 + 20;

        }

    }

    void sort(hero h[], int len)//按照年龄排序

    {

        for (int i = 0; i < len-1; i++)

        {

            for (int j = 0; j < len - i - 1; j++)

            {

                if (h[j].age > h[j+1].age)

                {

                    hero x = h[j];

                    h[j] = h[j + 1];

                    h[j + 1] = x;

                }

            }

        }

    }

    void printHero(hero h[], int len)

    {

        for (int i = 0; i < len; i++)

        {

            cout << h[i].hName << "  " << h[i].age << endl;

        }

    }

    int main()

    {

        srand((unsigned int)time(NULL));

        hero h[5];

        int len = sizeof(h) / sizeof(h[0]);

        creatValue(h, len);

        printHero(h, len);

        cout << endl;

        sort(h, len);//排序

        printHero(h, len);

        system("pause");

        return 0;

    }

    相关文章

      网友评论

          本文标题:5.结构体案例2

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