案例1
问题:
学校正在做毕设项目,每名老师带领5个学生,总共有3名老师,需求如下
设计学生和老师的结构体,其中在老师的结构体中,有老师姓名和一个存放5名学生的数组作为成员。学生的成员有姓名、考试分数,创建数组存放3名老师,通过函数给每个老师及所带的学生赋值,最终打印出老师数据以及老师所带的学生数据。
代码:
#include<iostream>
#include<string>
#include <ctime>
using namespace std;
struct Student
{
string name;
int score;
};
struct Teacher
{
string name;
Student s[5];
};
//给老师和学生赋值的函数
void allocateSpace(Teacher t[], int len)
{
string nameSeed = "ABCDE";
//给老师赋值
for (int i = 0; i < len; i++)
{
t[i].name = "teacher_";
t[i].name += nameSeed[i];
//给学生赋值
for (int j = 0; j < 5; j++)
{
//系统生成随机数
int score = rand() % 60 + 40; //生成0-99的随机数
t[i].s[j].name = "student_";
t[i].s[j].name += nameSeed[j];
t[i].s[j].score = score;
}
}
}
void printInfo(Teacher t[], int len)
{
for (int i = 0; i < len; i++)
{
cout << "老师姓名:" << t[i].name << endl;
for (int j = 0; j < 5; j++)
cout << "\t学生姓名:" << t[i].s[j].name << ",考试分数:" << t[i].s[j].score << endl;
}
}
int main()
{ //随机数种子
srand((unsigned int)time(NULL));
//1.创建3名老师的数组
Teacher t[3];
//2.通过函数给3名老师的信息赋值,并给老师带的学生信息赋值
int len = sizeof(t) / sizeof(t[0]);
allocateSpace(t, len);
//3.打印所有老师及所带学生的信息
printInfo(t, len);
system("pause");
return 0;
}
结果:
案例2
问题:
打印5名英雄的信息,并按照年龄进行升序排列
{“刘备”,23,“男”},
{“关羽”,22,“男”},
{“张飞”,20,“男”},
{“赵云”,21,“男”},
{“貂蝉”,19,“女”}
代码:
#include<iostream>
#include<string>
#include <ctime>
using namespace std;
struct hero
{
string name;
int age;
string sex;
};
void sort(hero people[],int len)
{
for(int i =0;i<len-1;i++)
{
for (int j = 0; j < len - i - 1; j++)
{
if (people[j].age > people[j + 1].age)
{
hero temp = people[j];
people[j] = people[j + 1];
people[j + 1] = temp;
}
}
}
cout << "排序后:" << endl;
for (int i = 0; i < 5; i++)
cout << people[i].name << people[i].age << people[i].sex << endl;
}
int main()
{
hero people[5] = {
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"},
};
cout << "排序前:" << endl;
for (int i = 0; i < 5; i++)
cout << people[i].name << people[i].age << people[i].sex << endl;
int len = sizeof(people) / sizeof(people[0]);
sort(people, len);
system("pause");
return 0;
}
结果: