章节概述
函数用于封装可复用的逻辑,结构体用于将相关数据组织为自定义类型。
两者是 C++ 面向过程编程的核心工具。
核心原理
1. 函数 — 逻辑封装
函数三要素:
- 参数传递: 按值(默认)、按引用 (int&)、按 const 引用
- 返回类型: void(无返回值)或具体类型
- 声明先于调用: 函数声明必须在调用之前
// 递归函数: gcd 辗转相除法
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }2. 结构体 — 数据封装
结构体 = 相关数据的集合,C++ 的 struct 可以包含:
- 数据成员
- 成员函数 (如 total()、isExcellent())
- 构造函数
struct Student {
string name;
int ch, ma, en;
int total() { return ch + ma + en; }
};3. 结构体与排序
配合 sort + 自定义比较函数:
bool cmp(Stu a, Stu b) {
return a.total() > b.total(); // 总分降序
}
sort(arr, arr + n, cmp);关键数据结构
- A_容器_Container — 结构体数组存储于 vector
- Q_排序_八大排序_Sorting — 结构体排序
P5735 距离函数
题目: 给出平面坐标上不在同一直线上的三个点,求三角形周长。
#include <cstdio>
#include <cmath>
double dist(double x1, double y1, double x2, double y2) {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
int main() {
double x1, y1, x2, y2, x3, y3;
scanf("%lf%lf%lf%lf%lf%lf", &x1, &y1, &x2, &y2, &x3, &y3);
double ans = dist(x1, y1, x2, y2)
+ dist(x1, y1, x3, y3)
+ dist(x2, y2, x3, y3);
printf("%.2f\n", ans);
return 0;
}P5737 闰年展示
题目: 输入 x 和 y,输出 [x,y] 区间内的闰年个数和所有闰年年份。
#include <iostream>
using namespace std;
bool isLeap(int y) {
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
int main() {
int x, y, cnt = 0, years[1000];
cin >> x >> y;
for (int i = x; i <= y; i++)
if (isLeap(i)) years[cnt++] = i;
cout << cnt << endl;
for (int i = 0; i < cnt; i++)
cout << years[i] << " ";
return 0;
}P5740 最厉害的学生
题目: N 个学生的姓名和语数英成绩,找出总分最高的学生。
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int chinese, math, english;
int total() { return chinese + math + english; }
};
int main() {
int n;
cin >> n;
Student best = {"", -1, -1, -1};
for (int i = 0; i < n; i++) {
Student s;
cin >> s.name >> s.chinese >> s.math >> s.english;
if (s.total() > best.total()) best = s;
}
cout << best.name << " " << best.chinese << " " << best.math << " " << best.english << endl;
return 0;
}推荐练习题(洛谷)
相关技巧
多平台练习
| 洛谷 | 本题单 | 竞赛基础 |
| POJ (北大) | PKU JudgeOnline | 经典题目,适合巩固 |
| HDU (杭电) | HDU OJ | 暑期多校训练 |
| Codeforces | Codeforces | 国际竞赛,适合提升 |