结构体

概念讲解

结构体定义

12345struct Student {
    string name;
    int age;
    int score;
};

结构体使用

123456Student s;
s.name = "张三";
s.age = 15;
s.score = 90;

cout << s.name << " " << s.score << endl;

结构体数组

123Student students[100];
students[0].name = "张三";
students[1].name = "李四";

结构体排序

12345bool cmp(Student a, Student b) {
    return a.score > b.score;
}

sort(students, students + n, cmp);

嵌套结构体

123456789struct Date {
    int year, month, day;
};

struct Student {
    string name;
    Date birthday;
    int score;
};

考点分析

初赛考查方式

  1. 选择题: 结构体定义
  2. 程序阅读: 结构体操作
  3. 填空题: 结构体排序

常见题型

  • 结构体定义
  • 结构体排序
  • 嵌套结构体

例题精讲

例题 1:结构体排序

题目: 按成绩从高到低排序学生。

解答:

12345678910struct Student {
    string name;
    int score;
};

bool cmp(Student a, Student b) {
    return a.score > b.score;
}

sort(students, students + n, cmp);

例题 2:嵌套结构体

题目: 使用嵌套结构体存储学生信息。

解答:

123456789101112131415struct Date {
    int year, month, day;
};

struct Student {
    string name;
    Date birthday;
    int score;
};

Student s;
s.name = "张三";
s.birthday.year = 2008;
s.birthday.month = 6;
s.birthday.day = 15;

练习题

  1. 定义一个表示点的结构体。
查看答案
123456789struct Point {
    int x;
    int y;
};

// 使用
Point p;
p.x = 10;
p.y = 20;
  1. 按姓名排序学生。
查看答案
12345678910struct Student {
    string name;
    int score;
};

bool cmp(Student a, Student b) {
    return a.name < b.name;  // 按姓名字典序升序
}

sort(students, students + n, cmp);
  1. 使用嵌套结构体存储信息。
查看答案
12345678910111213141516struct Date {
    int year, month, day;
};

struct Student {
    string name;
    Date birthday;
    int score;
};

Student s;
s.name = "张三";
s.birthday.year = 2008;
s.birthday.month = 6;
s.birthday.day = 15;
s.score = 90;

易错点

⚠️ 注意:

  1. 结构体定义末尾有分号
  2. 结构体可以嵌套
  3. 结构体排序要自定义比较函数
  4. 注意访问成员的方式