#include<iostream>
#include<string>
using namespace std;
struct Hero {
string name;
int age;
string sex;
};
void printHero(Hero* p,int length) {
for (int i = 0; i < length; i++)
{
cout << p[i].name << " " << p[i].age << " " << p[i].sex << " " << endl;
}
}
void bubble(Hero* p, int length) {
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length-i-1; j++)
{
//年龄大的放后面
if (p[j].age>p[j+1].age)
{
int temp = p[j + 1].age;
p[j + 1].age = p[j].age;
p[j].age = temp;
}
}
}
}
int main() {
//创建英雄数组,存放5位英雄
Hero heros[5] = {
{"小红",19,"女"},
{"小张",23,"男"},
{"小李",22,"男"},
{"小鹏",20,"男"},
{"小王",21,"男"}
};
//计算数组长度
int length = sizeof(heros) / sizeof(heros[0]);
//利用冒泡排序将五位英雄按照年龄升序排序
bubble(heros, length);
//打印输出排列好的数组
printHero(heros, length);
system("pause");
return 0;
}
注意: 一般情况下,我都习惯进行传地址操作,因为这样方便。如果不想修改原来的信息,应当在结构体类型指针前加上const