C++结构体、指针、数组、函数应用
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
//学生结构体
struct Student
{
//姓名
string sName;
//分数
int score;
};
struct Teacher
{
//姓名
string tName;
//学生数组
struct Student sArray[5];
};
//给老师和学生赋值的函数
void allocateSpace(struct Teacher *tArray, int len)
{
string nameSeed = "ABCDE";
//给老师开始赋值
for (int i = 0; i < len; i++)
{
tArray[i].tName = "Teacher_";
tArray[i].tName += nameSeed[i];
//通过循环给每名老师所带学生赋值
for (int j = 0; j < 5; j++)
{
tArray[i].sArray[j].sName = "Student_";
tArray[i].sArray[j].sName += nameSeed[i];
int random = rand() % 61 + 40;
tArray[i].sArray[j].score = random;
}
}
}
void printInfo(struct Teacher tArray[], int len)
{
for (int i = 0; i < len; i++)
{
cout << "老师姓名: " << tArray[i].tName << endl;
for (int j = 0; j < 5; j++)
{
cout << "学生姓名: " << tArray[i].sArray[j].sName <<
"考试的分数: " << tArray[i].sArray[j].score << endl;
}
}
}
int main()
{
//随机数种子
srand((unsigned)time(NULL));
//创建三明老师的数组
struct Teacher tArray[3];
//并且通过函数给3名老师的信息赋值,并给老师的学生信息赋值
int len = sizeof(tArray) / sizeof(tArray[0]);
allocateSpace(tArray, len);
//打印所有老师的信息赋值
printInfo(tArray, len);
system("pause");
}
案例二 结构体数组元素的交换
#include<iostream>
#include<string>
using namespace std;
struct Hero
{
string name;
int age;
string sex;
};
void bubbleSort(struct Hero hero[], int len)
{
for (int i = 0; i < len - 1; i++)
{
for (int j = 0; j < len - i - 1; j++)
{
if (hero[j].age > hero[j + 1].age)
{
struct Hero temp = hero[j];
hero[j] = hero[j + 1];
hero[j + 1] = temp;
}
}
}
}
void printHero(struct Hero hero[], int len)
{
for (int i = 0; i < len; i++)
{
cout << "姓名: " << hero[i].name << "年龄: " << hero[i].age << "性别: " << hero[i].sex << endl;
}
}
int main()
{
struct Hero hero[5] = {
{"刘备", 23, "男"},
{"张飞", 22, "男"},
{"关羽", 20, "男"},
{"赵云", 21, "男"},
{"貂蝉", 19, "女"},
};
int len = sizeof(hero) / sizeof(hero[0]);
for (int i = 0; i < len; i++)
{
cout << "姓名: " << hero[i].name << "年龄: " << hero[i].age << "性别: " << hero[i].sex << endl;
}
bubbleSort(hero, len);
printHero(hero, len);
system("pause");
}
[1] 引用黑马程序员 https://www.bilibili.com/video/BV1et411b73Z?p=70