#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;
}
网友评论