结构体进阶是 GESP 6 级核心考点,属于数据类型与内存管理类别。
核心内容:结构体嵌套、结构体数组、结构体指针、结构体做函数参数。
Student *p = &s;,访问成员用 p->name(箭头运算符)
易错点:
p.name(指针用箭头)→ ✅ p->name3
小明 95 北京
小红 88 上海
小刚 76 广州小明 95 北京
小红 88 上海
小刚 76 广州#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int score;
string city;
};
int main() {
int n;
cin >> n;
Student stu[100]; // 结构体数组,最多100人
for (int i = 0; i < n; i++) {
cin >> stu[i].name >> stu[i].score >> stu[i].city;
}
// 冒泡排序:按分数从高到低
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (stu[j].score < stu[j+1].score) {
Student temp = stu[j]; // 交换整个结构体
stu[j] = stu[j+1];
stu[j+1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
cout << stu[i].name << " " << stu[i].score << " " << stu[i].city << endl;
}
return 0;
}
temp = stu[j]),这是考试高频考点。排序时注意比较的是哪个成员。
p.name(指针用点号)→ ✅ p->name(指针必须用箭头){{"北京","海淀"}, 90, "张三"}s1 = s2;