结构体
#include<iostream>
using namespace std;
#include<string>
struct hero
{
string name;
int age;
string sex;
};
void bubblesort(struct 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 printarr(struct hero arr[], int len)
{
for (int i = 0; i < len; i++)
{
cout << arr[i].name << arr[i].age << arr[i].sex << endl;
}
}
int main()
{
/*
结构体定义语法: struct 结构体名 {结构体成员列表};
通过结构体创建变量有三种方式:
1.struct 结构体名 变量名
2.struct 结构体名 变量名={成员1值,成员2值...}
3.定义结构体时顺便创建变量
结构体数组:struct 结构体名 数组名[元素个数]={{},{},{}...}
给结构体数组中的元素赋值:数组名[i].属性=数值
结构体指针:结构体名 * 指针变量=&结构体变量
举个例子: struct student {string name,int age,int scores};//定义student结构体
student s1={"迪丽热巴",26,100};
student * p=&s1;
cout<<p->name<<p->age<<p->scores<<endl;//通过指针访问结构体变量中的数据->
随机数种子:srand(unsigned int)time(NULL);
随机数: rand()%num、rand()%num+num1
*/
//程序为按照年龄冒泡升序
struct hero arr[5] = { { "刘备", 23, "男" },
{ "关羽", 22, "男" },
{ "张飞", 20, "男" },
{ "赵云", 21, "男" },
{ "貂蝉", 19, "女" },
};
int len = sizeof(arr) / sizeof(arr[0]);
bubblesort(arr, len);
printarr(arr,len);
/*for (int i = 0; i < len; i++)
{
cout << arr[i].name << arr[i].age << arr[i].sex << endl;
}*/
system("pause");
return 0;
}