C++ 进阶 — 第 2 课
sort、set、map 处理一堆散装的数据。struct 把相关数据捆成一个新类型。s.score。class 多了成员函数,默认是私有的。假设你要管理学生信息。没有结构体的写法:
vector<string> names;
vector<int> scores;
vector<double> heights;
// 三个数组同步操作,稍有不慎就对乱了
names.push_back("Alice"); scores.push_back(95); heights.push_back(1.68);
// Alice 的成绩到底是 scores[0] 还是 scores[2]?全靠记忆力!
有了结构体:
struct Student {
string name;
int score;
double height;
};
Student s;
s.name = "Alice";
s.score = 95;
s.height = 1.68;
// 或者一行初始化
Student s2 = {"Bob", 87, 1.75};
一个人的所有信息绑在一起,不会散。
struct 类型名 {
成员1类型 成员1名;
成员2类型 成员2名;
// ...
}; // ← 别忘了分号!
// 访问成员用 . (点号)
Student s;
s.name = "Alice";
cout << s.score;
// C 风格数组
Student arr[100];
arr[0] = {"Alice", 95, 1.68};
cout << arr[0].name;
// vector(更好)
vector<Student> students;
students.push_back({"Alice", 95, 1.68});
students.push_back({"Bob", 87, 1.75});
for (Student s : students) {
cout << s.name << ": " << s.score << endl;
}
// 按成绩从高到低排序
bool cmpByScore(Student a, Student b) {
return a.score > b.score; // a 的分数 > b 的分数 → a 排前面
}
sort(students.begin(), students.end(), cmpByScore);
a.score < b.score。
struct 和 class 几乎一样,唯二区别:
| 对比项 | struct | class |
|---|---|---|
| 默认访问权限 | public | private |
| 习惯用法 | 纯数据的打包 | 数据 + 行为绑定 |
class Student {
public: // class 默认 private,必须加 public
string name;
int score;
void print() { // 数据和行为绑在一起
cout << name << ": " << score;
}
};
Student s;
s.name = "Alice";
s.print(); // Alice: 95
print()),用 class。struct。struct Student {
string name;
int score;
};
int main() {
vector<Student> stu;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string name; int score;
cin >> name >> score;
stu.push_back({name, score});
}
// 按分数降序排
sort(stu.begin(), stu.end(),
[](Student a, Student b) { return a.score > b.score; });
for (auto& s : stu)
cout << s.name << " " << s.score << endl;
}
struct 定义末尾那个分号别丢:}; 少写一个 ;,编译器会在后面莫名其妙的地方报错。class 默认是 private:成员想在外面访问,就得自己写 public:,不然全是“无法访问”。true 表示 a 排前面,> 是降序、< 是升序。push_back 自动扩容,不用提前猜 100 够不够。struct Point { int x, y; }; Point p = {3, 5}; 后 p.y 的值?struct Student { string name; int score; };score 判断,相等时返回 a.name < b.name。
struct 结尾少了分号,或者成员名字拼错。class 里那个成员前面有 public: 吗?cmp(a, b) 对两个样本该返回什么。students 在排序前后各打印一遍,看看是数据本身错了还是排序错了。. 访问。vector 能自动扩容更好用。return true 表示 a 排前面。private。