结构体案例

案例1

【案例描述】:

学校正在做毕设项目,每名老师带领5个学生,总共有3名老师,需求如下

设计学生和老师的结构体,其中在老师的结构体中,有老师姓名和一个存放5名学生的数组作为成员

学生的成员有姓名、考试分数,创建数组存放3名老师,通过函数给每个老师及所带的学生赋值

最终打印出老师数据以及老师所带的学生数据。

【demo】:

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

struct student
{
string name;
int score;
};

struct teacher
{
string name;
struct student stuArr[5];
};

void allocateSpace(teacher t[], int len)
{
string tName = "教师";
string sName = "学生";
string nameSeed = "ABCDE";

for (int i = 0; i < len; i++)
{
t[i].name = tName + nameSeed[i];
for (int j = 0; j < 5; j++)
{
t[i].stuArr[j].name = sName + nameSeed[j];
t[i].stuArr[j].score = rand() % 61 + 40;
}
}
}

void printTeachers(teacher t[], int len)
{
for (int i = 0; i < len; i++)
{
cout << "教师姓名:" << t[i].name << endl;
cout << "名下学生:" << endl;
for (int j = 0; j < 5; j++)
{
cout << "\t学生姓名:" << t[i].stuArr[j].name << " , 成绩:" << t[i].stuArr[j].score << endl;
}
}
}

int main()
{
struct teacher tea[3];
allocateSpace(tea, 3);
printTeachers(tea, 3);
return 0;
}

案例2

【案例描述】:

设计一个英雄的结构体,包括成员姓名,年龄,性别;创建结构体数组,数组中存放5名英雄。

通过冒泡排序的算法,将数组中的英雄按照年龄进行升序排序,最终打印排序后的结果。


五名英雄信息如下:

- {"刘备",23,"男"},

- {"关羽",22,"男"},

- {"张飞",20,"男"},

- {"赵云",21,"男"},

- {"貂蝉",19,"女"},

【demo】:

#include <iostream>
#include <string>

using namespace std;

struct hero
{
string name;
int age;
string gender;
};

// 按年龄排序
void bubbleSortByAge(hero h[], int len)
{
for (int i = 0; i < len - 1; i++)
{
for (int j = i + 1; j < len; j++)
{
if (h[i].age > h[j].age)
{
hero tmphero = h[i];
h[i] = h[j];
h[j] = tmphero;
}
}
}
}

// 打印英雄的信息
void printHeros(hero h[], int len)
{
for (int i = 0; i < len; i++)
{
cout << "姓名:" << h[i].name << " , 性别: " << h[i].gender << " , 年龄: " << h[i].age << endl;
}
}

int main()
{
// 定义英雄数组
struct hero h[5] =
{
{"刘备", 23, "男"},
{"关羽", 22, "男"},
{"张飞", 20, "男"},
{"赵云", 21, "男"},
{"貂蝉", 19, "女"}};
int len = sizeof(h) / sizeof(hero);
printHeros(h, len);
bubbleSortByAge(h, len);
cout << endl;
printHeros(h, len);

return 0;
}