【考点 · 4级】结构体(struct)——自定义数据类型,把多个不同类型的变量打包成一个整体。
🔹 定义方式:struct 名称 { 成员变量; }; 注意结尾分号不能丢!
🔹 访问成员:用 . 操作符,如 stu.name、stu.score。
🔹 初始化:可以用花括号直接赋值,也可以逐个成员赋值。
; 不能省略!这是考试中经典扣分点。还有,结构体变量之间可以直接用 = 赋值(整体拷贝),不需要逐个复制成员。
struct S{ int a; char b; }; 定义了几个变量?Student 结构体(包含 name: string, score: int)。#include <iostream>
using namespace std;
struct Student {
string name;
int score;
};
int main() {
int n;
cin >> n;
Student s[101];
for (int i = 0; i < n; i++)
cin >> s[i].name >> s[i].score;
// 冒泡排序(降序)
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - 1 - i; j++)
if (s[j].score < s[j+1].score) {
Student t = s[j]; // 交换整个结构体
s[j] = s[j+1];
s[j+1] = t;
}
for (int i = 0; i < n; i++)
cout << s[i].name << " " << s[i].score << endl;
return 0;
}
= 赋值,所以交换时定义一个临时 Student 变量即可,不需要逐个成员交换。
}; 的分号忘记写 — 编译报错且难以排查. 写成 ->(-> 是指针用的,4级先记 .){"小明", 95.5, 14} 会把 95.5 赋给 age(类型不匹配)struct A { int x; }; 定义了变量 — 实际只定义了类型,要 A a; 才创建变量= 整体赋值,但不能用 == 比较(C++17 前)