一、知识点整理
1. 结构体是什么
结构体可以把几个相关的数据打包成一个整体。比如一个学生既有名字又有分数,就把它们装进同一个 struct 里,以后一个变量就能代表一整个学生。
结构体定义的最后一定要写分号,漏掉会报错。
2. 定义与使用
struct Student{ string name; int score; }; 定义好后,Student a; 就是一块能装下这两项数据的内存。
访问成员用点号 .:a.name、a.score。成员不能直接当普通变量用,必须带上变量名和点号。
3. 结构体数组
Student s[3]; 就是 3 个学生依次排在数组里,下标从 0 开始:s[0]、s[1]、s[2] 各自都是一个完整的学生。
数组里所有元素必须是同一种类型,不能一个装学生、一个装别的东西。
4. 配合循环的三种典型用法
| 用法 | 写法要点 |
| 求和 | 循环里 sum = sum + s[i].score;(sum 写在循环外清零) |
| 统计 | 满足条件就 count++,同样写在循环外清零 |
| 找最值(擂台法) | 先用 0 号元素的分数当擂主,再从第 1 个开始依次挑战 |
案例一 结构体变量的定义与成员访问
登记表上,每个学生都有两栏:姓名和分数。小刚想用一段程序把这些信息存起来再读出来。
struct Student{
string name;
int score;
};
Student a;
a.name = "小明";
a.score = 95;
cout << a.name << endl;
cout << a.score << endl;
单选题
判断题
案例二 结构体数组
登记表上现在有 3 位学生。小刚用一个结构体数组把他们都装进去。
struct Student{
string name;
int score;
};
Student s[3];
s[0].name = "小明"; s[0].score = 90;
s[1].name = "小红"; s[1].score = 85;
s[2].name = "小刚"; s[2].score = 95;
cout << s[1].name << endl;
cout << s[2].score << endl;
单选题
判断题
案例三 结构体数组求和
老师要算一算 3 位学生的分数一共是多少,小刚用循环来累加。
struct Student{
string name;
int score;
};
Student s[3];
s[0].score = 90;
s[1].score = 85;
s[2].score = 95;
int sum = 0;
for(int i = 0; i < 3; i++){
sum = sum + s[i].score;
}
cout << sum << endl;
单选题
判断题
案例四 找分数最高的学生
老师想知道 3 位学生里谁的分数最高。小刚用'打擂台'的办法来比。
struct Student{
string name;
int score;
};
Student s[3];
s[0].name = "小明"; s[0].score = 90;
s[1].name = "小红"; s[1].score = 85;
s[2].name = "小刚"; s[2].score = 95;
int mx = s[0].score;
string who = s[0].name;
for(int i = 1; i < 3; i++){
if(s[i].score > mx){
mx = s[i].score;
who = s[i].name;
}
}
cout << who << " " << mx << endl;
单选题
判断题