结构体模板
将多个不同类型的数据打包在一起——自定义数据类型
结构体
struct
成员
自定义类型
GESP4
#include <bits/stdc++.h>
using namespace std;
struct Student {
string name;
int age;
double score;
};
// 带构造函数
struct Point {
int x, y;
Point(int x = 0, int y = 0) : x(x), y(y) {}
double dist() { return sqrt(x*x + y*y); }
};
// 运算符重载(排序用)
struct Node {
int val, cnt;
bool operator<(const Node &o) const {
return cnt != o.cnt ? cnt > o.cnt : val < o.val;
}
};
int main() {
Student s1 = {"小明", 12, 95.5};
cout << s1.name << " " << s1.score << endl;
Student stu[100];
int n; cin >> n;
for (int i = 0; i < n; i++)
cin >> stu[i].name >> stu[i].age >> stu[i].score;
// 按分数排序
sort(stu, stu + n, [](const Student &a, const Student &b) {
return a.score > b.score;
});
Point p(3, 4);
cout << p.dist() << endl; // 5
return 0;
}
📖 要点说明
struct默认成员是 public,适合数据封装- 可用构造函数初始化,
:初始化列表更高效 - 重载
<运算符让 sort 直接排序 - Lambda 也能做自定义排序
⚠️ 常见错误
- 结构体赋值用
{}但顺序必须与声明一致 - 排序比较函数不是严格弱序导致运行时错误
- 构造函数初始化列表顺序与声明不一致(编译器警告)