03-进阶基础/04-结构体
跳转到导航
跳转到搜索
结构体
结构体可以将多个不同类型的变量打包成一个新的类型。
定义结构体
struct Student
{
string name;
int age;
double score;
};
注意:右花括号后面要有分号。
使用结构体
Student s1; // 创建一个 Student 类型的变量
s1.name = "张三";
s1.age = 18;
s1.score = 95.5;
Student s2 = {"李四", 17, 88.0}; // 初始化列表
结构体访问成员
使用 . 运算符访问成员:
cout << s1.name << " " << s1.score;
结构体数组
Student a[100];
a[0].name = "王五";
a[0].age = 19;
结构体排序
方法一:定义比较函数
struct Student
{
string name;
int score;
};
bool cmp(const Student &a, const Student &b)
{
return a.score > b.score; // 按分数从高到低
}
// 使用
vector<Student> s(n);
sort(s.begin(), s.end(), cmp);
方法二:重载 < 运算符
struct Student
{
string name;
int score;
bool operator<(const Student &b) const
{
return score > b.score; // 按分数从高到低
}
};
// 使用:可以直接 sort,不需要 cmp 参数
sort(s.begin(), s.end());
结构体与 typedef / using
typedef long long ll;
// 等价于
using ll = long long;
struct Point { int x, y; };
using P = Point; // 给类型起别名
结构体嵌套
struct Point { int x, y; };
struct Rectangle
{
Point topLeft;
Point bottomRight;
};