首页 > 编程语言 > 详细

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

时间:2020-03-12 00:58:42      阅读:81      评论:0      收藏:0      [点我收藏+]
#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;

}

 

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

原文:https://www.cnblogs.com/hackerteen/p/12466567.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!