通过案例完成对结构的巩固:巩固结构体和数组,结构体赋值,地址传递用数组接收;巩固随机数的产生。
学习内容: 1.地址作为实参的情况
在函数传值时,传入数组名,相当于传入地址,要么用指针接收要么用数组接收
使用数组接收#include使用指针接收#include using namespace std; struct Student { string name; int age; string id; }; void print(struct Student s[], int len)//使用数组接收,利用地址偏移来完成遍历 { for (int i = 0; i < len; i++) { cout << "name:" < struct Student s[2] = { {"jack",18,"003" }, {"tom",19,"005"} }; int len = sizeof(s) / sizeof(s[0]); print(s, len);//传入数组名,相当于传入首地址 system("pause"); return 0; }
#include2.示例一#include using namespace std; struct Student { string name; int age; string id; }; void print(struct Student* p, int len) { for(int i =0; i cout << "name:" << p->name<<"tage:"< age<<"tid:"< id << endl; p++; } } int main() { struct Student s[2] = { {"jack",18,"003" }, {"tom",19,"005"} }; int len = sizeof(s) / sizeof(s[0]); print(s, len); system("pause"); return 0; }
案例描述:3位老师给5名学生打分,设计老师和学生的结构体,其中在老师的结构体中有老师的姓名和存放5名学生的数组;在学生的结构体中包括学生姓名和分数。通过创建函数给老师和所对应的学生赋值,并通过函数打印输出
#include定义结构体 主函数结构 分配函数 打印输出信息 最终结果展示 3.示例二#include using namespace std; struct Student { string stu_name; int scores; };//注意该处有分号 struct Teacher { string tea_name; struct Student s[5]; }; //给老师分配学生 void Allocatespace(struct Teacher* p, int len) { string name_seed = "ABCDE"; for (int i = 0; i < len; i++) { p->tea_name = "techer_"; p->tea_name += name_seed[i]; for (int j = 0; j < 5; j++) { p->s[j].stu_name = "student_"; p->s[j].stu_name += name_seed[j]; int random = rand() % 20 + 80; p->s[j].scores = random; } p++;//主要要递增!!!!!!!!!!!!! } } //打印输出整个信息 void Printinfo(struct Teacher t[], int len) { for (int i = 0; i < len; i++) { cout << "老师姓名:" << t[i].tea_name << endl; for (int j = 0; j < 5; j++) { cout << "学生姓名:" << t[i].s[j].stu_name << "**" << "学生的成绩:" << t[i].s[j].scores << endl; } cout << endl; } } int main() { srand((unsigned int)time(NULL)); struct Teacher t[3]; int len = sizeof(t) / sizeof(t[0]); Allocatespace(t, len); Printinfo(t, len); system("pause"); return 0; }
案例描述:设计一个英雄的结构体,包括姓名、年龄;创建结构体数组,含有5个成员;通过冒泡排序的算法升序排序;打印输出
#include#include using namespace std; struct Hero { string name; int age; }; void Sort(struct Hero h[], int len) { for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - i - 1; j++) { if (h[j].age > h[j + 1].age) { struct Hero temp = h[j]; h[j] = h[j + 1]; h[j + 1] = temp; } } } } void Print(struct Hero h[], int len) { for (int i = 0; i < len; i++) { cout << h[i].name << "t" << h[i].age << endl; } } int main() { struct Hero h[5] = { {"张三",56}, {"李四",35}, {"王五",24}, {"赵六",52}, {"陈七",39} }; int len = sizeof(h) / sizeof(h[0]); for (int i = 0; i < len; i++) { cout << h[i].name << "t" << h[i].age << endl; }; Sort(h,len); cout << "************" << endl;; Print(h, len); system("pause"); return 0; }



