实例1
#include <iostream>
#include <cstring>
#include <cstdlib>//为了使用random函数
#include <ctime>//为了使用随机数
using namespace std;
struct student{
int age;
int score;
string name;
};//定义学生结构体
struct teacher{
string name;
struct student sarray[5];
};//定义老师结构体
void allocatespace(struct teacher tarray[],int len){
string nameseed = "ABCDE";
for(int i = 0;i < len ;i++){
tarray[i].name = "teacher_";
tarray[i].name += nameseed[i];
for(int j = 0;j < 5;j ++){
tarray[i].sarray[j].name = "strudent_";
tarray[i].sarray[j].name += nameseed[j];
int random = rand() % 60 + 40 ;
tarray[i].sarray[j].score = random;
}}}//赋值的函数
printinfo(struct teacher tarray[],int len){
for(int i = 0;i < 3;i++){
cout << "老师的姓名:"<< tarray[i].name << endl;
for(int j = 0;j < 5;j++){
cout <<"\t学生的姓名: " << tarray[i].sarray[j].name;
cout <<" 学生的分数: "<< tarray[i].sarray[j].score << endl;
}
}
}//打印的函数
int main(){
srand((unsigned int)time(NULL));
struct teacher tarray[3];
int len = sizeof(tarray) / sizeof(tarray[0]);
allocatespace(tarray,len);
printinfo(tarray,len);
}
实例二
#include <iostream>
#include <cstring>
using namespace std;
struct hero{
string name;
int age;
string sex;
};
void bobble(struct hero array[],int len){
for(int i = 0;i < 4;i++){
for(int j = 0;j <5 - i - 1;j++){
if(array[j].age > array[j + 1].age){
struct hero temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
for(int i = 0;i < 5;i++){
cout << "姓名:"<<array[i].name<<" 年龄:"<<array[i].age<<" 性别:" <<array[i].sex<<endl ;
}
}//冒泡排序打印输出
int main(){
struct hero array[5] ={
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"},
};
int len = 5;
bobble(array,len);
}
7.29:复习了结构体,学习了嵌套结构体,改变结构体的值,使用指针和实际的值作改变,以及完成了两个实例题目,复习了结构体数组以及函数的使用。