6.8重学C++之【结构体-案例#2】

#include<iostream>
#include<string>
using namespace std;


/*
    结构体-案例#2
    三国英雄:5名英雄,通过冒泡排序按照年龄升序排列
*/


struct Hero{
    string name;
    int age;
    string sex;
};


void bubble_sort(struct Hero hero_array[], int len){
    for (int i=0; i<len-1; i++){ // i<len-1
        for (int j=0; j<len-1-i; j++){ // j<len-1-i
            if (hero_array[j].age > hero_array[j+1].age){
                struct Hero temp = hero_array[j];
                hero_array[j] = hero_array[j+1];
                hero_array[j+1] = temp;
            }
        }
    }
}


void print_hero(struct Hero hero_array[], int len){
    cout << "排序后:" << endl;
    for (int i=0; i<len; i++){
        cout << "姓名:" << hero_array[i].name << ",年龄:" << hero_array[i].age << ",性别:" << hero_array[i].sex << endl;
    }
}


int main(){
    struct Hero hero_array[5] = {
        {"刘备", 23, "男"},
        {"关羽", 22, "男"},
        {"张飞", 20, "男"},
        {"赵云", 21, "男"},
        {"貂蝉", 19, "女"}, // 注意此处最后一项后加逗号或者不加效果一样,都行
    };

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

    cout << "排序前:" << endl;
    for (int i=0; i<len; i++){
        cout << "姓名:" << hero_array[i].name << ",年龄:" << hero_array[i].age << ",性别:" << hero_array[i].sex << endl;
    }

    bubble_sort(hero_array, len);  // 值传递!?实参根据形参变了?!
    print_hero(hero_array, len);

    return 0;
}

posted @ 2021-03-11 12:05  yub4by  阅读(28)  评论(0编辑  收藏  举报