单元1 · C++ 环境与基础语法
编译器、main 入口、cout/cin、变量与常量、命名空间
- 入口:main 函数是入口;#include 引入头文件。
- 输出:cout << 输出、cin >> 输入,需
。 - 类型:int/double/string/bool;const 定义常量;auto 推导。
实训1.1 Hello World 与 iostream
编写第一个 C++ 程序,用 cout 输出问候语并说明命名空间。
C++ 程序从 main 函数开始;#include
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!" << endl;
cout << "C++ 是高效的系统级语言" << endl;
return 0;
}
实训1.2 变量与常量
声明 int、double、string、bool 变量和 const 常量并输出。
C++ 强类型;const 定义常量;string 需要
#include <iostream>
#include <string>
using namespace std;
int main() {
int age = 21;
double pi = 3.14159;
string name = "C++";
bool isFast = true;
const int MAX_SIZE = 100;
cout << "语言:" << name << endl;
cout << "年龄:" << age << endl;
cout << "圆周率:" << pi << endl;
cout << "是否高效:" << (isFast ? "是" : "否") << endl;
cout << "最大尺寸:" << MAX_SIZE << endl;
return 0;
}
实训1.3 输入与格式化输出
用 cin 读取两个整数,输出它们的和与平均值。
cin >> 读取输入;setprecision 控制小数位数,需
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int a, b;
cout << "请输入两个整数:";
cin >> a >> b;
cout << "和:" << a + b << endl;
cout << "平均值:" << fixed << setprecision(2)
<< (a + b) / 2.0 << endl;
return 0;
}
实训1.4 auto 与类型推导
用 auto 推导变量类型,用 sizeof 输出各类型字节数。
auto 让编译器推导类型;sizeof 返回字节数;不同平台结果可能不同。
#include <iostream>
using namespace std;
int main() {
auto n = 42; // int
auto pi = 3.14159; // double
auto msg = "hello"; // const char*
cout << "n: " << n << endl;
cout << "pi: " << pi << endl;
cout << "msg: " << msg << endl;
cout << "int 大小:" << sizeof(int) << " 字节" << endl;
cout << "double 大小:" << sizeof(double) << " 字节" << endl;
return 0;
}
单元2 · 数据类型与运算符
整型/浮点/字符/布尔、算术/比较/逻辑运算符、类型转换
- 运算:int 相除整除;% 取余;位运算 & | ^ << >>。
- 转换:static_cast
() 显式转换;窄化有风险。 - 逻辑:== != && || !;boolalpha 输出 true/false。
实训2.1 基础运算
给定整数 17 和 5,输出和、差、积、整除商、余数。
int 相除得 int(整除);% 取余;注意类型。
#include <iostream>
using namespace std;
int main() {
int a = 17, b = 5;
cout << "和:" << a + b << endl;
cout << "差:" << a - b << endl;
cout << "积:" << a * b << endl;
cout << "整除商:" << a / b << endl;
cout << "余数:" << a % b << endl;
return 0;
}
实训2.2 浮点运算与转换
计算半径为 7.5 的圆的周长与面积,π 取 3.14159。
浮点常量参与运算;static_cast
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double r = 7.5;
double pi = 3.14159;
double circumference = 2 * pi * r;
double area = pi * r * r;
cout << fixed << setprecision(4);
cout << "周长:" << circumference << endl;
cout << "面积:" << area << endl;
int a = 7, b = 2;
cout << "整除:" << a / b << endl;
cout << "浮点:" << static_cast<double>(a) / b << endl;
return 0;
}
实训2.3 比较与逻辑运算
a=8、b=12,输出 a>b、a!=b、a<10 && b>10、!(a==8)。
比较返回 bool;&& 与、|| 或、! 非。
#include <iostream>
using namespace std;
int main() {
int a = 8, b = 12;
cout << boolalpha;
cout << "a > b:" << (a > b) << endl;
cout << "a != b:" << (a != b) << endl;
cout << "a<10 && b>10:" << (a < 10 && b > 10) << endl;
cout << "!(a == 8):" << !(a == 8) << endl;
return 0;
}
实训2.4 位运算与自增自减
演示自增自减与位运算(与、或、异或、移位)的结果。
++/-- 前后置差异;& | ^ << >> 位运算。
#include <iostream>
using namespace std;
int main() {
int x = 5;
cout << "x++:" << x++ << ",之后 x=" << x << endl;
cout << "++x:" << ++x << ",之后 x=" << x << endl;
int a = 6, b = 3;
cout << "a & b:" << (a & b) << endl;
cout << "a | b:" << (a | b) << endl;
cout << "a ^ b:" << (a ^ b) << endl;
cout << "a << 1:" << (a << 1) << endl;
cout << "a >> 1:" << (a >> 1) << endl;
return 0;
}
单元3 · 流程控制:分支结构
if/else if/else、switch、三元
- 分支:if/else if/else 逐级判断。
- switch:case + break + default;支持 char。
- 三元:条件 ? 真 : 假,可嵌套。
实训3.1 if 判断成绩等级
成绩 score=85,输出等级:>=90 优秀、>=80 良好、>=60 及格、否则不及格。
if / else if / else 逐级判断。
#include <iostream>
using namespace std;
int main() {
int score = 85;
if (score >= 90) {
cout << "优秀" << endl;
} else if (score >= 80) {
cout << "良好" << endl;
} else if (score >= 60) {
cout << "及格" << endl;
} else {
cout << "不及格" << endl;
}
return 0;
}
实训3.2 switch 判断星期
用 switch 把数字 1-7 映射为星期,输入 4 输出对应星期。
switch 匹配 case;break 跳出;default 兜底。
#include <iostream>
using namespace std;
int main() {
int day = 4;
switch (day) {
case 1: cout << "星期一" << endl; break;
case 2: cout << "星期二" << endl; break;
case 3: cout << "星期三" << endl; break;
case 4: cout << "星期四" << endl; break;
case 5: cout << "星期五" << endl; break;
case 6: cout << "星期六" << endl; break;
case 7: cout << "星期日" << endl; break;
default: cout << "无效输入" << endl;
}
return 0;
}
实训3.3 三元与逻辑组合
判断 n=15 的奇偶,并用三元嵌套判断正负零。
三元 ?: 简洁表达分支;可嵌套但注意可读性。
#include <iostream>
using namespace std;
int main() {
int n = 15;
cout << (n % 2 == 0 ? "偶数" : "奇数") << endl;
int x = -3;
string type = x > 0 ? "正数" : (x < 0 ? "负数" : "零");
cout << x << " 是" << type << endl;
return 0;
}
实训3.4 字符与 switch 结合
用 switch 处理字符:元音字母提示、其它字母提示、数字提示。
switch 支持 char 类型;case 可合并多个值。
#include <iostream>
using namespace std;
int main() {
char ch = 'a';
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
cout << ch << " 是元音字母" << endl;
break;
default:
if (ch >= '0' && ch <= '9')
cout << ch << " 是数字" << endl;
else
cout << ch << " 是辅音或其他字符" << endl;
}
return 0;
}
单元4 · 循环结构
for、while、do-while、break/continue、嵌套循环
- for:标准三要素循环;嵌套打印表格。
- while:先判断;do-while 至少执行一次。
- 控制:break 终止、continue 跳过。
实训4.1 for 求和 1 到 100
用 for 循环计算 1+2+...+100 的和并输出。
标准 for 三要素;累加器初始 0。
#include <iostream>
using namespace std;
int main() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
cout << "1 到 100 的和:" << sum << endl;
return 0;
}
实训4.2 打印乘法表
输出 9x9 乘法表,每行一个乘数。
嵌套两层 for;内层次数随外层变化。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
cout << j << "x" << i << "=" << setw(2) << i * j << " ";
}
cout << endl;
}
return 0;
}
实训4.3 break 与 continue
输出 1 到 20 中能被 3 整除的数,遇到 15 用 break 结束。
continue 跳过当前迭代;break 终止循环。
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 20; i++) {
if (i == 15) break;
if (i % 3 != 0) continue;
cout << i << endl;
}
return 0;
}
实训4.4 while 与 do-while
分别用 while 和 do-while 求 1 到 50 的和,说明二者区别。
while 先判断后执行;do-while 至少执行一次。
#include <iostream>
using namespace std;
int main() {
int sum1 = 0, i = 1;
while (i <= 50) {
sum1 += i;
i++;
}
cout << "while 求和:" << sum1 << endl;
int sum2 = 0, j = 1;
do {
sum2 += j;
j++;
} while (j <= 50);
cout << "do-while 求和:" << sum2 << endl;
return 0;
}
单元5 · 函数
函数定义、参数传递、默认参数、重载、递归
- 函数:返回类型 + 参数列表 + return。
- 传参:值传递副本;引用 & 修改原变量。
- 进阶:默认参数、重载、递归。
实训5.1 定义求和函数
定义 add(int a, int b) 返回两数之和并调用输出。
函数声明 + 定义;return 返回值;参数按值传递。
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
cout << "add(10, 20) = " << add(10, 20) << endl;
cout << "add(3, 7) = " << add(3, 7) << endl;
return 0;
}
实训5.2 默认参数
定义 greet(string name, string greeting = "你好"),测试默认与自定义。
默认参数在函数声明中给值;未传时使用默认。
#include <iostream>
#include <string>
using namespace std;
string greet(string name, string greeting = "你好") {
return greeting + "," + name + "!";
}
int main() {
cout << greet("小明") << endl;
cout << greet("小红", "早上好") << endl;
return 0;
}
实训5.3 引用参数与值传递
写 swap 函数交换两个变量的值,分别用值传递与引用传递对比。
引用 & 直接操作原变量;值传递只改副本。
#include <iostream>
using namespace std;
void swapByValue(int a, int b) {
int t = a;
a = b;
b = t;
}
void swapByRef(int &a, int &b) {
int t = a;
a = b;
b = t;
}
int main() {
int x = 10, y = 20;
swapByValue(x, y);
cout << "值传递后:" << x << ", " << y << "(未交换)" << endl;
swapByRef(x, y);
cout << "引用传递后:" << x << ", " << y << "(已交换)" << endl;
return 0;
}
实训5.4 函数重载与递归
实现 int/float 两个版本的 max 重载;用递归求阶乘。
重载按参数类型区分;递归必须有终止条件。
#include <iostream>
using namespace std;
int max(int a, int b) {
return a > b ? a : b;
}
double max(double a, double b) {
return a > b ? a : b;
}
long long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
cout << "max(3, 7) = " << max(3, 7) << endl;
cout << "max(3.5, 2.8) = " << max(3.5, 2.8) << endl;
cout << "5! = " << factorial(5) << endl;
return 0;
}
单元6 · 数组与字符串
数组、指针与数组、C 风格字符串、string 类
- 数组:固定长度;sizeof 求元素个数。
- string:+ 拼接、find/substr/replace/size。
- 二维:[行][列] 声明与遍历。
实训6.1 数组遍历求最值
声明 int arr[5] = {12,45,7,89,33},遍历求最大值与平均值。
数组下标从 0 开始;sizeof(arr)/sizeof(arr[0]) 求长度。
#include <iostream>
using namespace std;
int main() {
int arr[5] = {12, 45, 7, 89, 33};
int n = sizeof(arr) / sizeof(arr[0]);
int max = arr[0], sum = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > max) max = arr[i];
sum += arr[i];
}
cout << "最大值:" << max << endl;
cout << "平均值:" << (double)sum / n << endl;
return 0;
}
实训6.2 数组逆序
将数组 {1,2,3,4,5} 逆序输出并交换首尾元素。
双指针交换首尾;或从后往前遍历输出。
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0, j = n - 1; i < j; i++, j--) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
cout << "逆序后:";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
实训6.3 string 类操作
用 string 类做拼接、查找、截取、替换、长度统计。
string 支持 + 拼接;find/size/substr/replace 常用方法。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "Hello";
string s2 = " C++";
string s = s1 + s2;
cout << "拼接:" << s << endl;
cout << "长度:" << s.size() << endl;
cout << "查找 C++ 位置:" << s.find("C++") << endl;
cout << "截取前 5 个:" << s.substr(0, 5) << endl;
s.replace(6, 3, "World");
cout << "替换后:" << s << endl;
return 0;
}
实训6.4 二维数组
定义 3x3 矩阵,计算每行之和并输出。
二维数组 [行][列];外层遍历行、内层遍历列。
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; i++) {
int sum = 0;
for (int j = 0; j < 3; j++)
sum += matrix[i][j];
cout << "第 " << i + 1 << " 行之和:" << sum << endl;
}
return 0;
}
单元7 · 指针与动态内存
指针基础、指针与数组、new/delete、引用
- 指针:& 取地址、* 解引用;指针算术。
- 动态内存:new/delete 分配释放堆内存。
- 引用:别名,必须初始化、不可改绑。
实训7.1 指针基础
声明变量 x=42,取指针 p 指向 x,通过指针修改并输出。
& 取地址、* 解引用;指针存储变量的地址。
#include <iostream>
using namespace std;
int main() {
int x = 42;
int *p = &x;
cout << "x 的值:" << x << endl;
cout << "x 的地址:" << p << endl;
cout << "通过指针读取:" << *p << endl;
*p = 100;
cout << "修改后 x:" << x << endl;
return 0;
}
实训7.2 指针遍历数组
用指针遍历数组并求和,说明指针算术运算。
指针 + n 指向下一个元素;p++ 移动指针。
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
int *p = arr;
for (int i = 0; i < n; i++) {
sum += *(p + i);
cout << "arr[" << i << "] = " << *(p + i) << endl;
}
cout << "指针求和:" << sum << endl;
return 0;
}
实训7.3 new/delete 动态分配
用 new 动态分配数组并初始化,使用后 delete 释放。
new 分配堆内存;delete[] 释放数组;避免内存泄漏。
#include <iostream>
using namespace std;
int main() {
int n = 5;
int *arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = (i + 1) * 10;
cout << "动态数组:";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
delete[] arr;
return 0;
}
实训7.4 引用与指针对比
演示引用的使用:引用必须初始化、修改引用即修改原变量。
引用是别名,声明后不可改绑;指针可重新指向。
#include <iostream>
using namespace std;
int main() {
int a = 10;
int &ref = a; // 引用:a 的别名
ref = 20; // 修改引用即修改 a
cout << "a = " << a << endl;
int b = 30;
int *p = &a; // 指针可重新指向
p = &b;
cout << "指针指向 b:" << *p << endl;
cout << "a 仍为:" << a << ",b 为:" << b << endl;
return 0;
}
单元8 · 面向对象
类、构造函数、封装、继承、多态
- 类:class + private/public + 构造函数。
- 继承:public 继承 + 初始化列表调用基类。
- 多态:virtual 虚函数 + 基类指针。
实训8.1 定义类与对象
定义 Student 类(name、score 私有成员,公有方法),实例化并调用。
class 定义类;private/public 访问控制;构造函数初始化。
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
double score;
public:
Student(string n, double s) : name(n), score(s) {}
string getInfo() {
return name + ",成绩 " + to_string(score) + " 分";
}
};
int main() {
Student stu("小明", 92.5);
cout << stu.getInfo() << endl;
return 0;
}
实训8.2 继承与派生
定义 Animal 基类和 Dog 派生类,Dog 调用基类构造函数并重写行为。
class Dog : public Animal 继承;构造函数初始化列表调用基类。
#include <iostream>
#include <string>
using namespace std;
class Animal {
protected:
string name;
public:
Animal(string n) : name(n) {}
virtual string speak() {
return "动物叫声";
}
};
class Dog : public Animal {
public:
Dog(string n) : Animal(n) {}
string speak() override {
return name + ":汪汪!";
}
};
int main() {
Dog dog("旺财");
cout << dog.speak() << endl;
return 0;
}
实训8.3 封装与 getter/setter
用私有成员 + 公有方法实现银行账户的存取款与余额查询。
private 封装数据;公有方法提供带校验的访问接口。
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance = 0;
public:
void deposit(double amount) {
if (amount > 0)
balance += amount;
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount acc;
acc.deposit(1000);
acc.withdraw(300);
cout << "余额:" << acc.getBalance() << " 元" << endl;
return 0;
}
实训8.4 虚函数与多态
用基类指针数组存储不同形状对象,虚函数实现多态求面积。
virtual 定义虚函数;基类指针调用派生类实现。
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() = 0;
virtual ~Shape() {}
};
class Circle : public Shape {
private:
double r;
public:
Circle(double radius) : r(radius) {}
double area() override { return 3.14159 * r * r; }
};
class Square : public Shape {
private:
double s;
public:
Square(double side) : s(side) {}
double area() override { return s * s; }
};
int main() {
Shape *shapes[] = {new Circle(3), new Square(5)};
double total = 0;
for (int i = 0; i < 2; i++) {
total += shapes[i]->area();
delete shapes[i];
}
cout << "总面积:" << total << endl;
return 0;
}
单元9 · STL 容器
vector、map、迭代器、算法
- vector:动态数组,push_back/insert/erase。
- map:键值对自动排序,[] 访问、count 判断。
- 算法:sort/find/accumulate/count_if/max_element。
实训9.1 vector 动态数组
用 vector 存储整数,添加元素、遍历、求最大值。
vector 动态扩容;push_back 添加;size() 长度。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
nums.push_back(12);
nums.push_back(45);
nums.push_back(7);
nums.push_back(89);
cout << "大小:" << nums.size() << endl;
int max = nums[0];
for (int v : nums) {
if (v > max) max = v;
cout << v << " ";
}
cout << endl << "最大值:" << max << endl;
return 0;
}
实训9.2 vector 常用操作
演示 vector 的插入、删除、排序、查找元素。
insert/erase/sort/find 组合使用;sort 在
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {5, 3, 8, 1, 9};
nums.insert(nums.begin() + 1, 10);
nums.erase(nums.begin());
sort(nums.begin(), nums.end());
cout << "排序后:";
for (int v : nums) cout << v << " ";
cout << endl;
auto it = find(nums.begin(), nums.end(), 8);
cout << "8 是否存在:" << (it != nums.end() ? "是" : "否") << endl;
return 0;
}
实训9.3 map 键值容器
用 map
map 自动按键排序;[] 插入/访问;erase 删除。
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> ages;
ages["张三"] = 20;
ages["李四"] = 22;
ages["王五"] = 24;
ages["李四"] = 23;
ages.erase("王五");
for (auto &kv : ages) {
cout << kv.first << ":" << kv.second << " 岁" << endl;
}
if (ages.count("张三")) {
cout << "张三的年龄:" << ages["张三"] << endl;
}
return 0;
}
实训9.4 算法库综合
用
accumulate 求和;count_if 条件计数;max_element 找最大。
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {12, 45, 7, 89, 33, 60};
int sum = accumulate(nums.begin(), nums.end(), 0);
cout << "总和:" << sum << endl;
int passed = count_if(nums.begin(), nums.end(),
[](int n) { return n >= 60; });
cout << "及格数:" << passed << endl;
auto maxIt = max_element(nums.begin(), nums.end());
cout << "最大值:" << *maxIt << endl;
return 0;
}
单元10 · 文件与流
文件读写、字符串流、异常处理
- 文件:ofstream 写、ifstream 读、getline 逐行。
- 字符串流:stringstream 解析字符串。
- 异常:throw + try/catch;runtime_error。
实训10.1 写文件
用 ofstream 向文件写入多行内容。
ofstream 写文件;<< 输出;close 关闭。
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out("data.txt");
if (!out) {
cout << "打开文件失败" << endl;
return 1;
}
out << "第一行内容" << endl;
out << "第二行内容" << endl;
out.close();
cout << "写入完成" << endl;
return 0;
}
实训10.2 读文件
用 ifstream 逐行读取文件内容并统计行数。
ifstream 读文件;getline 逐行读取;eof 判断结束。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream out("data.txt");
out << "hello" << endl << "world" << endl << "c++" << endl;
out.close();
ifstream in("data.txt");
string line;
int count = 0;
while (getline(in, line)) {
cout << "行" << ++count << ":" << line << endl;
}
in.close();
cout << "总行数:" << count << endl;
return 0;
}
实训10.3 字符串流
用 stringstream 拆分字符串为单词并统计个数。
stringstream 可像流一样读写字符串;>> 提取单词。
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string text = "C++ is powerful and fast";
stringstream ss(text);
string word;
int count = 0;
while (ss >> word) {
cout << word << endl;
count++;
}
cout << "单词总数:" << count << endl;
return 0;
}
实训10.4 异常处理
用 try/catch 捕获除零异常与自定义异常。
throw 抛异常;catch 捕获;std::exception 基类。
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(double a, double b) {
if (b == 0)
throw runtime_error("除数不能为 0");
return a / b;
}
int main() {
try {
cout << divide(10, 2) << endl;
cout << divide(10, 0) << endl;
} catch (const exception &e) {
cout << "捕获异常:" << e.what() << endl;
}
return 0;
}
单元11 · Lambda 与泛型
Lambda 表达式、模板函数、auto
- Lambda:[捕获](参数){体};配合 STL 算法。
- 模板:template
泛型函数与类。 - auto:自动类型推导简化声明。
实训11.1 Lambda 表达式
定义 Lambda 求和并立即调用;捕获外部变量。
Lambda 语法 [捕获](参数){ 体 };[] 按值捕获、[&] 按引用。
#include <iostream>
using namespace std;
int main() {
auto add = [](int a, int b) { return a + b; };
cout << "add(3, 4) = " << add(3, 4) << endl;
int base = 100;
auto addBase = [base](int x) { return base + x; };
cout << "addBase(5) = " << addBase(5) << endl;
int counter = 0;
auto inc = [&counter]() { counter++; };
inc();
inc();
cout << "counter = " << counter << endl;
return 0;
}
实训11.2 Lambda 与 STL 结合
用 Lambda 配合 sort、for_each、count_if 处理数据。
Lambda 作为回调传入算法;sort 自定义比较。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {12, 45, 7, 89, 33};
sort(nums.begin(), nums.end(),
[](int a, int b) { return a > b; });
cout << "降序:";
for_each(nums.begin(), nums.end(),
[](int v) { cout << v << " "; });
cout << endl;
int big = count_if(nums.begin(), nums.end(),
[](int v) { return v > 50; });
cout << "大于 50 的个数:" << big << endl;
return 0;
}
实训11.3 函数模板
定义模板函数 maxOf 支持任意可比较类型。
template
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T maxOf(T a, T b) {
return a > b ? a : b;
}
int main() {
cout << "maxOf(3, 7) = " << maxOf(3, 7) << endl;
cout << "maxOf(3.5, 2.8) = " << maxOf(3.5, 2.8) << endl;
cout << "maxOf('a', 'z') = " << maxOf('a', 'z') << endl;
return 0;
}
实训11.4 类模板
定义 Pair 类模板存储两个值并输出。
template
#include <iostream>
#include <string>
using namespace std;
template <typename T1, typename T2>
class Pair {
private:
T1 first;
T2 second;
public:
Pair(T1 a, T2 b) : first(a), second(b) {}
void show() {
cout << "(" << first << ", " << second << ")" << endl;
}
};
int main() {
Pair<int, string> p1(1, "one");
Pair<double, double> p2(3.14, 2.71);
p1.show();
p2.show();
return 0;
}
单元12 · 综合项目实训
综合运用 C++ 知识完成项目
- 综合:结构体、容器、算法、Lambda 组合。
- 工程化:排序统计、查找删除、循环交互。
实训12.1 学生成绩管理系统
用结构体和 vector 实现学生管理:添加、按成绩排序、输出成绩单。
struct + vector + sort + Lambda 组合。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct Student {
string name;
double chinese;
double math;
double average() { return (chinese + math) / 2; }
};
int main() {
vector<Student> students = {
{"张三", 90, 85},
{"李四", 78, 92},
{"王五", 88, 76}
};
sort(students.begin(), students.end(),
[](const Student &a, const Student &b) {
return a.average() > b.average();
});
cout << "姓名 语文 数学 平均" << endl;
double total = 0;
for (auto &s : students) {
cout << s.name << " " << s.chinese << " "
<< s.math << " " << s.average() << endl;
total += s.average();
}
cout << "平均分:" << total / students.size() << endl;
return 0;
}
实训12.2 词频统计器
统计文本中单词出现次数,输出出现最多的单词。
stringstream 拆词 + map 统计 + 遍历找最大值。
#include <iostream>
#include <map>
#include <sstream>
#include <string>
using namespace std;
int main() {
string text = "cplusplus is powerful cplusplus is fast cplusplus is fun";
stringstream ss(text);
string word;
map<string, int> freq;
while (ss >> word) {
freq[word]++;
}
string maxWord;
int maxCount = 0;
for (auto &kv : freq) {
cout << kv.first << ":" << kv.second << endl;
if (kv.second > maxCount) {
maxCount = kv.second;
maxWord = kv.first;
}
}
cout << "出现最多:" << maxWord << "," << maxCount << " 次" << endl;
return 0;
}
实训12.3 通讯录管理
用 vector
结构体 + vector + find_if + erase 组合。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct Contact {
string name;
string phone;
};
int main() {
vector<Contact> book;
book.push_back({"张三", "13800000001"});
book.push_back({"李四", "13800000002"});
auto print = [&]() {
for (auto &c : book)
cout << c.name << ":" << c.phone << endl;
};
print();
string target = "张三";
auto it = find_if(book.begin(), book.end(),
[&](const Contact &c) { return c.name == target; });
if (it != book.end())
cout << "找到:" << it->name << ":" << it->phone << endl;
book.erase(remove_if(book.begin(), book.end(),
[](const Contact &c) { return c.name == "李四"; }),
book.end());
cout << "删除后:" << endl;
print();
return 0;
}
实训12.4 猜数字游戏
实现猜数字游戏:随机生成 1-100 的数,循环提示大了/小了,记录次数。
rand 随机数 + while 循环 + cin 输入 + 次数统计。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(nullptr));
int target = rand() % 100 + 1;
int guess, attempts = 0;
cout << "猜一个 1-100 的数字:" << endl;
do {
cout << "请输入:";
cin >> guess;
attempts++;
if (guess > target)
cout << "大了!" << endl;
else if (guess < target)
cout << "小了!" << endl;
else
cout << "恭喜!猜了 " << attempts << " 次" << endl;
} while (guess != target);
return 0;
}