c++
c++手册
注:此文大部分是AI生成,作者排版 :::info[c++98]
C++98 特性
1. 类与面向对象(Class & OOP)
C++98 支持类、继承、虚函数和多态。你可以定义基类和派生类,通过 virtual 关键字实现运行时多态。
怎么用:在基类中声明虚函数,在派生类中重写它,然后通过基类指针或引用调用,会自动调用实际对象的版本。
例如:
class Animal {
public:
virtual void speak() { cout << "Animal sound\n"; }
};
class Dog : public Animal {
public:
void speak() { cout << "Woof!\n"; }
};
Animal* a = new Dog();
a->speak(); // 输出 Woof!,这就是多态
好处:代码可扩展,便于维护;缺点是虚函数有轻微性能开销。
2. 模板(Templates)
模板让你编写与类型无关的通用代码,比如一个排序函数可以用在 int、double 或自定义类型上。
怎么用:用 template<typename T> 声明,函数或类内部使用 T 作为占位类型。
例如:
template<typename T>
T max(T a, T b) { return a > b ? a : b; }
int x = max(3, 5); // T 是 int
double y = max(1.2, 3.4); // T 是 double
好处:避免重复代码;注意:模板代码必须在头文件中定义(通常),否则链接会出错。
3. STL 容器与算法
STL 提供了如 vector、list、map 等容器,以及 sort、find 等通用算法。
怎么用:包含对应头文件(如 <vector>, <algorithm>),直接使用。
例如:
vector<int> v;
v.push_back(10);
v.push_back(20);
sort(v.begin(), v.end()); // 排序
好处:高效、安全、标准化;缺点是早期编译器对 STL 支持不完整。
4. 异常处理(try/catch/throw)
用于处理运行时错误,比如文件打不开、内存分配失败等。
怎么用:用 throw 抛出异常,try 包裹可能出错的代码,catch 捕获并处理。
例如:
try {
if (error) throw runtime_error("Something wrong");
} catch (const exception& e) {
cout << "Error: " << e.what() << endl;
}
好处:分离错误处理逻辑;注意:不要滥用,异常有性能开销。
5. 命名空间(namespace)
避免不同库之间的名字冲突,比如两个库都有叫 print 的函数。
怎么用:用 namespace 名字 { ... } 定义,用 :: 访问成员。
例如:
namespace MyLib {
void print() { cout << "MyLib\n"; }
}
MyLib::print();
好处:组织代码清晰;标准库所有内容都在 std 命名空间里。
6. 输入输出流(iostream)
替代 C 的 printf/scanf,类型安全,支持运算符重载。
怎么用:用 cin >> x 读入,cout << x 输出。
例如:
int age;
cin >> age;
cout << "You are " << age << " years old." << endl;
好处:类型安全,不会因格式符错误崩溃;缺点是比 printf 慢一点。
7. const 与引用
const 表示“不可修改”,引用是变量的别名。常用于函数参数避免拷贝。
怎么用:函数参数写成 const Type&。
例如:
void print(const string& s) {
cout << s << endl; // 不拷贝字符串,也不修改它
}
好处:提升性能,防止意外修改;这是 C++98 最佳实践之一。
::: :::info[c++11]
C++11 新特性
1. auto 自动类型推导
让编译器根据初始化表达式自动推断变量类型。
怎么用:声明变量时用 auto 替代具体类型。
例如:
auto i = 42; // i 是 int
auto v = vector<string>(); // v 是 vector<string>
for (auto it = v.begin(); ...) // it 是迭代器类型
好处:简化复杂类型书写(尤其迭代器);注意:auto 会忽略顶层 const 和引用,如需保留要用 const auto&。
2. decltype
获取一个表达式的类型,但不执行该表达式。
怎么用:decltype(表达式) 变量;
例如:
int x = 1, y = 2;
decltype(x + y) z = 3; // z 是 int
好处:在模板编程中非常有用,比如返回类型依赖参数类型时。
3. 统一初始化(花括号 {})
用 {} 初始化任何类型,包括数组、结构体、容器等。
怎么用:替换 = 或构造函数调用。
例如:
int a{10};
vector<int> v{1, 2, 3};
pair<string, int> p{"age", 25};
好处:语法统一,防止“最 vexing parse”问题;还能禁止窄化转换(如 double 赋给 int 会报错)。
4. 范围 for 循环
遍历容器或数组中每个元素,无需手动写 begin/end。
怎么用:for (元素声明 : 容器)
例如:
vector<int> nums{1, 2, 3};
for (auto& n : nums) n *= 2; // 修改每个元素
for (const auto& n : nums) cout << n << " "; // 只读
好处:代码简洁,不易出错;适用于所有支持 begin()/end() 的类型。
5. nullptr
类型安全的空指针常量,替代 NULL(通常为 0)。
怎么用:任何需要空指针的地方用 nullptr。
例如:
void f(int*);
f(nullptr); // 明确调用指针版本
好处:解决函数重载歧义;NULL 在 C++98 中是整数 0,容易调错函数。
6. Lambda 表达式
定义匿名函数,常用于 STL 算法或事件回调。
怎么用:[捕获](参数) -> 返回类型 { 函数体 },返回类型可省略。
例如:
auto add = [](int a, int b) { return a + b; };
cout << add(2, 3) << endl; // 输出 5
vector<int> v{1, 2, 3};
for_each(v.begin(), v.end(), [](int x) { cout << x << " "; });
好处:代码更紧凑;捕获列表 [=] 按值捕获,[&] 按引用捕获。
7. 智能指针(unique_ptr, shared_ptr)
自动管理动态内存,防止内存泄漏。
怎么用:
unique_ptr:独占资源,不能拷贝,可用make_unique创建。shared_ptr:共享资源,引用计数为 0 时自动释放。
例如:auto p = make_unique<int>(42); // C++14 起支持 make_unique,C++11 可写 unique_ptr<int>(new int(42)) shared_ptr<int> sp = make_shared<int>(100);好处:不再需要手动 delete;避免悬空指针和重复释放。
8. 移动语义(Move Semantics)
通过右值引用(T&&)“移动”资源而非拷贝,提升性能。
怎么用:定义移动构造函数和移动赋值运算符。
例如:
class MyString {
char* data;
public:
MyString(MyString&& other) noexcept : data(other.data) {
other.data = nullptr; // “偷走”资源
}
};
好处:临时对象(如函数返回值)不再深拷贝,大幅提高效率;STL 容器已全面支持移动。
9. = default 和 = delete
显式控制特殊成员函数的生成或禁用。
怎么用:
= default:让编译器生成默认版本。= delete:禁止使用某个函数。
例如:class NonCopyable { public: NonCopyable() = default; NonCopyable(const NonCopyable&) = delete; };好处:明确设计意图;防止意外拷贝(如单例类)。
10. override 和 final
override:标记虚函数重写,若签名不匹配则编译报错。final:禁止继承类或重写函数。
怎么用:class Base { public: virtual void foo(); virtual void bar() final; }; class Derived : public Base { public: void foo() override; // 正确 // void bar() override; // 错误!bar 是 final };好处:提高代码安全性,避免拼写错误导致“新增函数”而非“重写”。
11. constexpr
声明可在编译期计算的函数或变量。
怎么用:在变量或函数前加 constexpr。
例如:
constexpr int square(int x) { return x * x; }
constexpr int s = square(5); // 编译期计算,s 是编译时常量
好处:可用于数组大小、模板参数等需要常量的场合;提升性能。
12. enum class(强类型枚举)
枚举值不会隐式转换为整数,且不会污染外层作用域。
怎么用:enum class 名字 { 值 };
例如:
enum class Color { Red, Green };
Color c = Color::Red;
// int x = c; // 错误!不能隐式转为 int
好处:类型安全,避免命名冲突;推荐替代 C++98 的普通 enum。
13. 原生多线程支持
标准库提供 thread、mutex、future 等,无需依赖 pthread 或 Windows API。
怎么用:
void task() { cout << "Thread running\n"; }
thread t(task);
t.join(); // 等待线程结束
好处:跨平台;但需注意数据竞争,配合 mutex 使用。
14. 新容器:array、unordered_map 等
array<T, N>:固定大小数组,栈上分配,比 C 数组安全。unordered_map/unordered_set:基于哈希表,平均 O(1) 查找。
怎么用:array<int, 3> arr{1, 2, 3}; unordered_map<string, int> m; m["age"] = 25;好处:
array有 size() 方法,支持范围 for;unordered_map比 map 快(无序)。
15. static_assert
编译期断言,用于模板或常量检查。
怎么用:static_assert(条件, "错误信息");
例如:
static_assert(sizeof(int) == 4, "int must be 4 bytes");
好处:在编译时报错,比运行时 assert 更早发现问题。
:::
:::info[c++14]
C++14 新特性
1. 函数返回类型自动推导(auto 函数)
- 是什么:函数可用
auto作返回类型,编译器根据return推导。 - 怎么用:
// C++14 auto multiply(int a, double b) { return a * b; // 返回 double } - 对比 C++11:
// C++11 必须显式写出返回类型(或用 decltype,很麻烦) template<typename T, typename U> auto multiply(T a, U b) -> decltype(a * b) { return a * b; } - 什么时候用:泛型函数返回类型复杂但能从
return推出;简化模板代码。 - 注意:所有
return必须推导为同一类型。
2. 广义 Lambda 表达式
-
是什么:Lambda 参数可用
auto,捕获列表可初始化变量。 -
怎么用:
// 泛型 lambda auto add = [](auto a, auto b) { return a + b; }; int x = add(1, 2); // OK double y = add(1.5, 2.5); // OK // 初始化捕获(模拟移动捕获) auto p = std::make_unique<int>(42); auto lambda = [q = std::move(p)]() { return *q; }; -
对比 C++11:
// C++11 不支持 auto 参数,必须写仿函数或模板 struct Add { template<typename T, typename U> auto operator()(T a, U b) -> decltype(a + b) { return a + b; } }; Add add; -
什么时候用:写一次性的泛型回调;需要“移动捕获”资源(如
unique_ptr)。
3. decltype(auto)
-
是什么:保留表达式的引用和 const 属性。
-
怎么用:
int x = 42; int& getRef() { return x; } auto a = getRef(); // a 是 int(拷贝) decltype(auto) b = getRef(); // b 是 int&(引用) -
对比 C++11:
// C++11 无法简洁实现,需手动写 decltype(getRef()) decltype(getRef()) c = getRef(); // 等价于 decltype(auto) -
什么时候用:实现完美转发的包装函数;需要保持左值/右值语义。
4. 二进制字面量与数字分隔符
- 是什么:
0b前缀表示二进制,'分隔数字。 - 怎么用:
int flags = 0b1010'0000; // 二进制权限标志 long big = 1'000'000'000; // 10亿,易读 - 对比 C++11:
// C++11 只能写十六进制或十进制,难读 int flags = 0xA0; // 不直观 long big = 1000000000; // 容易数错零 - 什么时候用:位操作、硬件编程、定义大常量。
5. std::make_unique
- 是什么:安全创建
unique_ptr的工厂函数。 - 怎么用:
auto p = std::make_unique<std::vector<int>>(10, 0); - 对比 C++11:
// C++11 没有 make_unique,只能裸 new(不安全) std::unique_ptr<std::vector<int>> p(new std::vector<int>(10, 0)); // 若 new 后构造 shared_ptr 时抛异常,可能泄漏 - 什么时候用:所有需要动态分配独占资源的场合;替代裸
new。
:::
:::info[c++17]
C++17 新特性
1. 结构化绑定
-
是什么:将 tuple/pair/结构体解包到多个变量。
-
怎么用:
std::map<std::string, int> m{{"age", 25}}; for (const auto& [key, value] : m) { std::cout << key << ": " << value << "\n"; } auto [x, y] = std::make_pair(1, 2.5); -
对比 C++11/14:
// C++11 需要 .first/.second for (const auto& kv : m) { std::cout << kv.first << ": " << kv.second << "\n"; } auto p = std::make_pair(1, 2.5); int x = p.first; double y = p.second; -
什么时候用:遍历 map;处理返回 pair/tuple 的函数;访问结构体成员。
2. if constexpr
-
是什么:编译期条件分支,未选中代码不实例化。
-
怎么用:
template<typename T> void process(T t) { if constexpr (std::is_integral_v<T>) { std::cout << "Int: " << t << "\n"; } else { std::cout << "Other: " << t << "\n"; } } -
对比 C++11:
// C++11 需用 SFINAE 或 traits,代码复杂 template<typename T> typename std::enable_if<std::is_integral<T>::value>::type process(T t) { /* int 版 */ } template<typename T> typename std::enable_if<!std::is_integral<T>::value>::type process(T t) { /* other 版 */ } -
什么时候用:模板中根据类型走不同逻辑;避免编译错误。
3. 类模板参数推导(CTAD)
- 是什么:构造对象时自动推导模板参数。
- 怎么用:
std::pair p(1, 2.5); // → pair<int, double> std::vector v{1, 2, 3}; // → vector<int> - 对比 C++11/14:
// C++11 必须显式写类型 std::pair<int, double> p(1, 2.5); std::vector<int> v{1, 2, 3}; - 什么时候用:创建标准库对象;自定义类提供 deduction guide 后也可用。
4. std::optional
-
是什么:表示“可能有值,也可能无值”。
-
怎么用:
std::optional<int> findValue(const std::string& key) { if (map.count(key)) return map[key]; else return std::nullopt; } if (auto val = findValue("age")) { std::cout << *val << "\n"; } -
对比 C++11:
// C++11 常用 -1、nullptr、bool+out param,不安全 int findValue(const std::string& key, bool& found) { if (exists) { found = true; return value; } else { found = false; return -1; } // -1 可能是合法值! } -
什么时候用:函数可能无返回值;可选配置项;替代 magic number。
5. 并行 STL
- 是什么:STL 算法支持并行执行。
- 怎么用:
std::vector<double> data(1000000); std::sort(std::execution::par, data.begin(), data.end()); - 对比 C++11:
// C++11 需手动开线程 + 分块 + 合并,极易出错 // 或依赖 OpenMP/TBB 等第三方库 - 什么时候用:大数据集(>10k 元素)+ CPU 密集型操作;无数据竞争。
:::
:::info[c++20]
C++20 新特性
1. 概念(Concepts)
-
是什么:为模板参数添加约束。
-
怎么用:
template<std::integral T> T add(T a, T b) { return a + b; } -
对比 C++11/17:
// C++17 用 enable_if,错误信息难懂 template<typename T> std::enable_if_t<std::is_integral_v<T>, T> add(T a, T b) { return a + b; } // 调用 add("hello", "world") 会报几百行模板错误 -
什么时候用:编写泛型库;让模板接口契约清晰;提升编译错误可读性。
2. 范围(Ranges)库
- 是什么:链式、惰性、函数式风格的 STL。
- 怎么用:
auto result = vec | std::views::filter([](int x) { return x > 0; }) | std::views::transform([](int x) { return x * x; }); - 对比 C++11/17:
// C++17 需多步操作,可能产生临时容器 std::vector<int> temp; std::copy_if(vec.begin(), vec.end(), std::back_inserter(temp), pred); std::transform(temp.begin(), temp.end(), temp.begin(), op); - 什么时候用:数据流水线处理;避免中间容器;偏好函数式风格。
3. 三路比较 <=>
- 是什么:一个运算符生成全部比较操作。
- 怎么用:
struct Point { int x, y; auto operator<=>(const Point&) const = default; }; - 对比 C++11/17:
// C++17 需手写 6 个运算符 bool operator==(const Point& a, const Point& b) { return a.x==b.x && a.y==b.y; } bool operator!=(const Point& a, const Point& b) { return !(a == b); } bool operator<(const Point& a, const Point& b) { /* ... */ } // 还要 <=, >, >=... - 什么时候用:自定义类型需支持排序、set/map 的 key;减少样板代码。
4. std::span
- 是什么:非拥有式连续内存视图。
- 怎么用:
void process(std::span<int> data) { for (int& x : data) x *= 2; } std::vector<int> v = {1,2,3}; process(v); // 自动转 span - 对比 C++11/17:
// C++17 常用 T* + size_t,不安全 void process(int* data, size_t n) { // 无法知道是否越界;不能直接传 vector } - 什么时候用:API 设计接受任意数组类型;替代指针+长度参数。
:::
:::info[c++23]
C++23 新特性
1. std::print
-
是什么:安全、高效、支持 UTF-8 的格式化输出。
-
怎么用:
std::print("Hello, {}! Age: {}\n", name, age); std::println(u8"🌍 你好!"); -
对比 C++20 及以前:
// C++20 用 iostream(冗长) std::cout << "Hello, " << name << "! Age: " << age << "\n"; // 或 printf(不安全) printf("Hello, %s! Age: %d\n", name.c_str(), age); // 类型不匹配会崩溃 -
什么时候用:所有输出场景;调试、日志、CLI 工具;输出中文/emoji。
-
作者注:大部分编译器用不了,请谨慎使用
2.
std::generator -
是什么:协程实现的惰性生成器。
-
怎么用:
std::generator<int> fib() { int a = 0, b = 1; while (true) { co_yield a; auto tmp = a + b; a = b; b = tmp; } } int count = 0; for (int n : fib()) { if (count++ >= 10) break; std::cout << n << " "; } -
对比 C++20:
// C++20 需手动实现迭代器(几十行代码) class FibIterator { /* ... */ }; class Fibonacci { /* begin/end */ }; -
什么时候用:无限序列;懒加载大数据;替代复杂迭代器。
3. explicit(bool)
-
是什么:根据条件决定是否
explicit。 -
怎么用:
template<typename T> class Wrapper { public: explicit(!std::is_arithmetic_v<T>) Wrapper(T x) : val(x) {} }; Wrapper w1 = 42; // OK(int 是算术类型) Wrapper w2 = "hello"; // Error!需 explicit 构造 -
对比 C++17:
// C++17 无法实现,要么全 explicit,要么全隐式 template<typename T> class Wrapper { explicit Wrapper(T x); // 所有类型都必须显式构造 }; -
什么时候用:设计泛型包装类;对简单类型允许隐式转换,复杂类型禁止。
4. UTF-8 增强
- 是什么:源文件默认 UTF-8,
char8_t标准化。 - 怎么用:
const char8_t* s = u8"你好"; std::print(u8"🌍 {}\n", s); // C++23 print 原生支持 - 对比 C++20 及以前:
// C++20 在 Windows 输出中文需 SetConsoleOutputCP(CP_UTF8) // 且 u8"" 是 char8_t*,不能直接传给 cout(需转换) std::cout << u8"你好"; // C++20 可能编译错误或乱码 - 什么时候用:国际化应用;源码含非 ASCII 字符;跨平台输出 Unicode。
::: :::info[c++可用的容器]
从 C 到 C++23:容器的进化史
容器是存储和组织数据的基本工具。从 C 的裸指针到 C++23 的多维视图,C++ 容器体系越来越安全、高效、表达力强。
🧱 第一阶段:C 语言 —— “手动内存管理时代”
1. 原生数组(T arr[N])
int numbers[5] = {1, 2, 3, 4, 5};
- 优点:栈上分配,速度快。
- 缺点:
- 大小固定;
- 无法获取长度(
sizeof(arr)/sizeof(arr[0])易错); - 不能作为函数返回值;
- 越界不检查 → 缓冲区溢出。
2. 动态数组(malloc + free)
int* p = (int*)malloc(10 * sizeof(int));
// 使用...
free(p);
- 风险:忘记
free→ 内存泄漏;重复free→ 崩溃;无类型安全。
💡 C 的“容器”本质是指针 + 手动管理,灵活但危险。
🌱 第二阶段:C++98 —— STL 诞生,安全容器登场
C++98 引入 标准模板库(STL),提供类型安全、自动内存管理的容器。
| 容器 | 特点 | 适用场景 |
|---|---|---|
std::vector<T> |
动态数组,连续内存 | 需要随机访问、频繁尾部增删 |
std::list<T> |
双向链表 | 频繁中间插入/删除 |
std::deque<T> |
双端队列 | 首尾都需高效插入 |
std::set<T> / std::map<K,V> |
红黑树,有序 | 需要自动排序、去重、对数查找 |
std::stack<T> / std::queue<T> |
适配器(基于 deque) | LIFO / FIFO 场景 |
示例(C++98):
#include <vector>
#include <map>
#include <iostream>
int main() {
std::vector<int> v;
v.push_back(10);
v.push_back(20);
std::map<std::string, int> ages;
ages["Alice"] = 25;
std::cout << ages["Alice"] << "\n"; // 输出 25
}
✅ 优势:自动内存管理、类型安全、迭代器统一接口。
❌ 局限:无哈希表、无固定数组、无线程安全。
⚡ 第三阶段:C++11/14 —— 移动语义 + 新容器
新增容器:
| 容器 | 说明 |
|---|---|
std::array<T, N> |
固定大小数组,栈上分配,支持 .size() |
std::unordered_set<T> / std::unordered_map<K,V> |
哈希表实现,平均 O(1) 查找 |
示例对比:
▶ 固定数组:C vs C++11
// C
int arr[3] = {1, 2, 3};
int len = sizeof(arr)/sizeof(arr[0]); // 易错!传参后失效
// C++11
std::array<int, 3> arr{1, 2, 3};
std::cout << arr.size() << "\n"; // 安全,可传参
▶ 哈希表:C++98 无 vs C++11 有
// C++11
std::unordered_map<std::string, int> m;
m["count"] = 100; // 平均 O(1),比 map 快(无序)
✅ 移动语义让
vector插入临时对象时避免拷贝,性能飞跃。
🧩 第四阶段:C++17 —— 实用主义增强
新增容器/工具:
| 类型 | 说明 |
|---|---|
std::optional<T> |
表示“可能有值” |
std::variant<T...> |
类型安全的 union |
std::any |
可存任意类型的容器 |
<filesystem> 中的 path |
路径也是一种“容器” |
示例:替代 C 风格错误码
// C 风格:用 -1 表示失败(不安全)
int find_index(const char* str, char c) {
for (int i = 0; str[i]; ++i)
if (str[i] == c) return i;
return -1; // -1 可能是合法索引?
}
// C++17
std::optional<size_t> find_index(std::string_view s, char c) {
for (size_t i = 0; i < s.size(); ++i)
if (s[i] == c) return i;
return std::nullopt; // 明确“无结果”
}
✅ 更安全、更清晰地表达“无值”语义。
🌐 第五阶段:C++20 —— 范围、视图、协程容器
新增容器/视图:
| 类型 | 说明 |
|---|---|
std::span<T> |
非拥有式连续内存视图 |
std::ranges 视图(如 views::filter) |
惰性、链式操作序列 |
| 协程生成器(需手动实现) | 惰性序列(C++23 标准化) |
示例:span 替代 C 风格指针+长度
// C 风格(危险)
void process(int* data, size_t n) {
// 不知道是否越界
}
// C++20
void process(std::span<int> data) {
for (int& x : data) x *= 2; // 安全,带边界信息
}
std::vector<int> v = {1,2,3};
process(v); // 自动转 span
范围视图(替代临时容器):
auto evens_squared = vec
| std::views::filter([](int x) { return x % 2 == 0; })
| std::views::transform([](int x) { return x * x; });
// 无临时 vector,内存高效
✅ 视图(view)不是容器,而是“窗口”,零拷贝操作数据流。
🚀 第六阶段:C++23 —— 多维、生成器、格式化输出
新增容器/工具:
| 类型 | 说明 |
|---|---|
std::generator<T> |
协程实现的惰性生成器 |
std::mdspan<T> |
多维数组非拥有视图 |
std::print |
虽非容器,但极大简化容器输出 |
示例 1:std::generator 替代手写迭代器
// C++23
std::generator<int> range(int start, int end) {
for (int i = start; i < end; ++i)
co_yield i;
}
for (int x : range(0, 5)) {
std::cout << x << " "; // 输出:0 1 2 3 4
}
对比 C++20:需几十行代码实现迭代器类。
示例 2:std::mdspan 处理矩阵
std::vector<double> data(12); // 3x4 矩阵
std::mdspan md{data.data(), 3, 4};
double val = md[1, 2]; // 访问第1行第2列
适用于科学计算、AI 张量库(如替代 Eigen 的部分功能)。
示例 3:轻松输出容器(C++23)
std::vector v{1, 2, 3};
std::print("{}\n", v); // 输出:[1, 2, 3]
C++20 及以前需手写循环或依赖第三方库。
📊 容器选择指南(终极对照表)
| 需求 | 推荐容器 | C++ 版本 |
|---|---|---|
| 动态数组,随机访问 | std::vector<T> |
C++98 |
| 固定大小数组 | std::array<T, N> |
C++11 |
| 快速查找(无序) | std::unordered_map<K,V> |
C++11 |
| 快速查找(有序) | std::map<K,V> |
C++98 |
| 频繁中间插入/删除 | std::list<T> |
C++98 |
| 首尾高效操作 | std::deque<T> |
C++98 |
| 函数可能无返回值 | std::optional<T> |
C++17 |
| 存储多种互斥类型 | std::variant<T...> |
C++17 |
| 通用类型存储 | std::any |
C++17 |
| 安全传递数组参数 | std::span<T> |
C++20 |
| 惰性数据流处理 | std::views::xxx |
C++20 |
| 无限/懒加载序列 | std::generator<T> |
C++23 |
| 多维数组视图 | std::mdspan<T> |
C++23 |
| 路径操作 | std::filesystem::path |
C++17 |
✅ 总结:C → C++23 容器的进化逻辑
| 时代 | 核心思想 | 代表技术 |
|---|---|---|
| C | “你负责一切” | 指针 + malloc |
| C++98 | “安全封装” | vector, map, iterator |
| C++11 | “性能 + 实用” | unordered_map, array, move |
| C++17 | “表达意图” | optional, variant, any |
| C++20 | “组合与视图” | ranges, span, concepts |
| C++23 | “生产力 + 现代化” | generator, mdspan, print |
🔚 现代 C++ 容器哲学:
- 安全(无裸指针、无越界)
- 高效(移动语义、视图零拷贝)
- 表达力强(optional 表达“无值”,generator 表达“流”)
- 开发者友好(print 直接输出 vector)
从此,告别 malloc 和缓冲区溢出,拥抱 安全、简洁、高性能 的现代 C++ 容器世界! |
|---|
| :::info[STL] |
📘 STL 全家桶:C++ 标准模板库完整指南(截至 C++23)
STL(Standard Template Library)是 C++ 最强大、最成熟的泛型库。它不仅包含容器,还包括 算法、迭代器、仿函数、适配器、范围(Ranges)等,共同构成一套高效、通用、类型安全的数据处理体系。
本文将 一次性列出 STL 中所有官方组件,包括:
- ✅ 所有容器(16 个)
- ✅ 所有算法(约 120+ 个)
- ✅ 迭代器类别与工具
- ✅ 函数对象与绑定器
- ✅ 范围(Ranges)视图与算法(C++20+)
- ✅ 工具类(如
pair,tuple,optional等)
全部按标准分类,附头文件与用途说明。
一、STL 五大核心组件
STL 由以下五部分组成(源自 Alexander Stepanov 设计):
| 组件 | 作用 |
|---|---|
| 1. 容器(Containers) | 存储数据的结构 |
| 2. 算法(Algorithms) | 操作数据的通用函数 |
| 3. 迭代器(Iterators) | 连接容器与算法的“泛化指针” |
| 4. 函数对象(Function Objects / Functors) | 可调用对象,用于定制行为 |
| 5. 适配器(Adapters) | 改造接口(容器适配器、迭代器适配器、函数适配器) |
C++17 后新增 范围(Ranges),C++20 起成为第一等公民。
二、所有 STL 容器(共 16 个)
🔸 序列容器(5)
| 容器 | 头文件 | 特点 |
|---|---|---|
std::vector<T> |
<vector> |
动态数组,连续内存 |
std::deque<T> |
<deque> |
双端队列 |
std::list<T> |
<list> |
双向链表 |
std::forward_list<T> |
<forward_list> |
单向链表(C++11) |
std::array<T, N> |
<array> |
固定数组(C++11) |
🔸 关联容器(4,有序)
| 容器 | 头文件 |
|---|---|
std::set<K> / multiset<K> |
<set> |
std::map<K,V> / multimap<K,V> |
<map> |
🔸 无序关联容器(4,哈希)
| 容器 | 头文件 |
|---|---|
std::unordered_set<K> / unordered_multiset<K> |
<unordered_set> |
std::unordered_map<K,V> / unordered_multimap<K,V> |
<unordered_map> |
🔸 容器适配器(3)
| 适配器 | 头文件 | 底层默认容器 |
|---|---|---|
std::stack<T> |
<stack> |
deque |
std::queue<T> |
<queue> |
deque |
std::priority_queue<T> |
<queue> |
vector + heap |
✅ 总计:5 + 4 + 4 + 3 = 16 个
三、所有 STL 算法(按功能分类,共 120+ 个)
所有算法定义在 <algorithm> 和 <numeric> 中。
1. 非修改序列操作(Non-modifying)
#include <algorithm>
for_each– 对每个元素执行函数find,find_if,find_if_not– 查找元素count,count_if– 计数mismatch– 找出第一个不匹配位置equal– 判断两区间是否相等search,search_n– 子序列查找lexicographical_compare– 字典序比较
2. 修改序列操作(Modifying)
copy,copy_if,copy_n,copy_backwardmove,move_backward(C++11)fill,fill_n– 填充transform– 映射变换generate,generate_n– 生成值replace,replace_if,replace_copy– 替换swap,swap_ranges,iter_swapreverse,reverse_copyrotate,rotate_copyshuffle,random_shuffle(C++17 弃用)unique,unique_copy– 去重(需先排序)
3. 划分操作(Partitioning)
is_partitionedpartition,partition_copystable_partitionpartition_point
4. 排序及相关操作(Sorting)
sort,stable_sortpartial_sort,partial_sort_copynth_element– 快速选择第 n 小元素is_sorted,is_sorted_untillower_bound,upper_bound– 二分查找equal_range,binary_search
5. 二分搜索(已含在排序中,但常单列)
lower_bound,upper_bound,equal_range,binary_search
6. 集合操作(Set operations on sorted ranges)
mergeinplace_mergeincludes– 判断子集set_union,set_intersectionset_difference,set_symmetric_difference
7. 堆操作(Heap)
make_heap,push_heap,pop_heap,sort_heapis_heap,is_heap_until
8. 最小/最大操作
min,max,minmaxmin_element,max_element,minmax_elementclamp(C++17)– 限制值在 [low, high] 区间
9. 比较操作
lexicographical_comparelexicographical_compare_three_way(C++20,配合<=>)
10. 排列操作(Permutations)
next_permutation,prev_permutation
11. 数值算法(<numeric>)
#include <numeric>
iota(C++11)– 填充递增序列[0,1,2,...]accumulate– 累加(可自定义操作)reduce(C++17)– 并行累加transform_reduce(C++17)inner_product– 内积adjacent_difference– 相邻差分partial_sum– 前缀和
12. 并行算法(C++17)
通过执行策略启用:
#include <execution>
std::sort(std::execution::par, v.begin(), v.end());
支持策略:
seq– 顺序执行par– 并行执行par_unseq– 并行且可向量化
✅ 几乎所有
<algorithm>中的算法都支持执行策略(除少数如for_each_n)。
四、迭代器(Iterators)
迭代器类别(C++20 前)
| 类别 | 支持操作 | 示例容器 |
|---|---|---|
| 输入/输出迭代器 | 单向读/写 | istream_iterator |
| 前向迭代器 | 多次遍历 | forward_list, unordered_map |
| 双向迭代器 | ++, -- |
list, map |
| 随机访问迭代器 | +, -, [], < |
vector, deque, array |
| 连续迭代器(C++17 概念) | 指向连续内存 | vector, array |
迭代器工具(<iterator>)
begin(),end()– 通用获取迭代器(支持 C 数组)cbegin(),cend()– const 版本rbegin(),rend()– 反向迭代器crbegin(),crend()next(),prev()– 安全移动迭代器distance()– 计算距离advance()– 移动迭代器back_inserter,front_inserter,inserter– 插入迭代器适配器ostream_iterator,istream_iterator– 流迭代器
五、函数对象(Functors)与绑定器
1. 标准函数对象(<functional>)
算术
plus<T>,minus<T>,multiplies<T>,divides<T>,modulus<T>,negate<T>
比较
equal_to<T>,not_equal_to<T>,greater<T>,less<T>,greater_equal<T>,less_equal<T>
逻辑
logical_and<T>,logical_or<T>,logical_not<T>
⚠️ C++20 起,这些被标记为 deprecated,推荐使用 lambda 或
<=>。
2. 绑定与适配器(C++11 后基本被 lambda 取代)
std::bind(C++11)std::mem_fn– 成员函数转函数对象std::function<T>– 通用可调用包装器std::reference_wrapper<T>– 引用语义包装
六、C++20 Ranges 库(革命性升级)
Ranges 将“算法 + 视图”组合成管道式操作。
1. 范围算法(<ranges>)
几乎所有传统算法都有 ranges 版本:
std::ranges::sort(v)std::ranges::find(v, 42)std::ranges::transform(v, out, f)
✅ 优势:自动取 begin/end,更安全,支持投影(projection)。
2. 视图(Views,惰性、零拷贝)
#include <ranges>
views::all– 包装为 viewviews::filter(pred)– 过滤views::transform(f)– 映射views::take(n),views::drop(n)– 截取views::join– 展平嵌套范围views::split(delim)– 分割字符串views::iota(start, end)– 生成整数序列views::common– 转为 common rangeviews::reverse– 反向views::keys,views::values– 用于 map
示例:
auto squares = numbers
| std::views::filter([](int x) { return x > 0; })
| std::views::transform([](int x) { return x * x; });
七、其他重要工具类(虽非“算法/容器”,但属 STL 生态)
| 类型 | 头文件 | 用途 |
|---|---|---|
std::pair<T1,T2> |
<utility> |
二元组 |
std::tuple<T...> |
<tuple> |
多元组(C++11) |
std::optional<T> |
<optional> |
可空值(C++17) |
std::variant<T...> |
<variant> |
类型安全 union(C++17) |
std::any |
<any> |
任意类型容器(C++17) |
std::string_view |
<string_view> |
字符串只读视图(C++17) |
std::span<T> |
<span> |
连续内存视图(C++20) |
std::mdspan<T> |
<mdspan> |
多维数组视图(C++23) |
std::generator<T> |
<generator> |
协程生成器(C++23) |
std::print |
<print> |
格式化输出容器(C++23) |
八、总结:STL 全家桶清单
| 类别 | 数量 | 说明 |
|---|---|---|
| 容器 | 16 | 5 序列 + 4 有序 + 4 无序 + 3 适配器 |
| 算法 | ~120+ | <algorithm> + <numeric> |
| 迭代器工具 | 20+ | <iterator> |
| 函数对象 | 10+ | <functional>(部分已弃用) |
| Ranges 视图 | 15+ | C++20,惰性组合 |
| 现代工具类 | 10+ | optional, variant, span 等 |
✅ 使用建议
- 优先用
vector+ranges+auto:现代 C++ 最佳实践。 - 能用算法就别手写循环:
std::find比 for 更安全、更表达意图。 - 避免裸指针传数组:用
span或vector。 - 输出容器用 C++23
std::print:std::print("{}\n", vec); - 性能关键路径考虑并行算法:
std::execution::par
🌟 STL 的哲学:
“用最少的代码,表达最清晰的意图,获得最高的性能。”
掌握这份清单,你就掌握了 C++ STL 的全部武器库! ::::info[代码补充]{open} 、
📘 STL 完整实战手册(带代码示例,截至 C++23)
编译建议:
- C++17:
g++ -std=c++17 file.cpp- C++20:
g++ -std=c++20 file.cpp- C++23:
g++ -std=c++23 file.cpp(GCC 13+ / Clang 16+)
一、所有 STL 容器(16 个)+ 代码示例
1. 序列容器
✅ std::vector
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 3};
v.push_back(4);
for (int x : v) std::cout << x << " "; // 1 2 3 4
}
✅ std::deque
#include <deque>
int main() {
std::deque<int> dq;
dq.push_front(0);
dq.push_back(1);
// 支持首尾 O(1)
}
✅ std::list
#include <list>
int main() {
std::list<int> lst = {1, 2, 3};
lst.insert(lst.begin(), 0); // 中间插入快
lst.sort(); // list 自带 sort(因无随机迭代器)
}
✅ std::forward_list(C++11)
#include <forward_list>
int main() {
std::forward_list<int> fl = {3, 1, 2};
fl.sort(); // 单向链表,内存更省
}
✅ std::array(C++11)
#include <array>
int main() {
std::array<int, 3> arr = {1, 2, 3};
std::cout << arr.size() << "\n"; // 3,编译期已知
}
2. 关联容器(有序)
✅ std::map
#include <map>
#include <iostream>
int main() {
std::map<std::string, int> m;
m["age"] = 25;
for (const auto& [k, v] : m) // C++17 结构化绑定
std::cout << k << ": " << v << "\n";
}
✅ std::set
#include <set>
int main() {
std::set<int> s = {3, 1, 2};
// 自动排序去重 → {1,2,3}
}
multiset/multimap允许重复键,用法类似。
3. 无序关联容器(哈希)
✅ std::unordered_map(C++11)
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> um;
um["count"] = 100;
// 平均 O(1) 查找,无序
}
✅ std::unordered_set
#include <unordered_set>
int main() {
std::unordered_set<int> us = {1, 2, 3};
if (us.count(2)) { /* 存在 */ }
}
4. 容器适配器
✅ std::stack
#include <stack>
int main() {
std::stack<int> s;
s.push(1); s.push(2);
std::cout << s.top(); // 2
s.pop();
}
✅ std::queue
#include <queue>
int main() {
std::queue<int> q;
q.push(1); q.push(2);
std::cout << q.front(); // 1
}
✅ std::priority_queue
#include <queue>
int main() {
std::priority_queue<int> pq; // 大顶堆
pq.push(3); pq.push(1); pq.push(4);
std::cout << pq.top(); // 4
}
二、STL 算法(分类 + 代码)
1. 查找与计数
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 3, 2, 4};
// 查找
auto it = std::find(v.begin(), v.end(), 2);
if (it != v.end())
std::cout << "Found at index: " << (it - v.begin()) << "\n";
// 条件查找
auto it2 = std::find_if(v.begin(), v.end(), [](int x) { return x > 3; });
// 计数
int cnt = std::count(v.begin(), v.end(), 2); // 2
}
2. 排序与二分查找
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {3, 1, 4, 1, 5};
std::sort(v.begin(), v.end()); // [1,1,3,4,5]
// 二分查找
bool has3 = std::binary_search(v.begin(), v.end(), 3); // true
// 找边界
auto low = std::lower_bound(v.begin(), v.end(), 1); // 第一个 ≥1
auto up = std::upper_bound(v.begin(), v.end(), 1); // 第一个 >1
}
3. 变换与生成
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 3};
// 平方
std::vector<int> squares(v.size());
std::transform(v.begin(), v.end(), squares.begin(),
[](int x) { return x * x; });
// 填充
std::vector<int> arr(5);
std::fill(arr.begin(), arr.end(), 42); // 全为 42
// 生成递增序列(C++11)
std::vector<int> seq(5);
std::iota(seq.begin(), seq.end(), 0); // [0,1,2,3,4]
}
4. 去重与唯一化
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 2, 3, 3, 3};
// unique 要求先排序,且只移动不删除
auto last = std::unique(v.begin(), v.end());
v.erase(last, v.end()); // [1,2,3]
}
5. 数值算法(<numeric>)
#include <numeric>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 3, 4};
int sum = std::accumulate(v.begin(), v.end(), 0); // 10
int prod = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>{}); // 24
std::vector<int> prefix(v.size());
std::partial_sum(v.begin(), v.end(), prefix.begin()); // [1,3,6,10]
}
6. 并行算法(C++17)
#include <algorithm>
#include <execution>
#include <vector>
int main() {
std::vector<double> data(1000000, 1.0);
// 并行排序(大数据才有效)
std::sort(std::execution::par, data.begin(), data.end());
}
三、迭代器工具示例
#include <iterator>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 3};
// 安全移动
auto it = v.begin();
auto next_it = std::next(it, 2); // 指向 3
// 插入迭代器(避免手写 push_back)
std::vector<int> out;
std::copy(v.begin(), v.end(), std::back_inserter(out));
// 流迭代器(从 cin 读)
// std::vector<int> input;
// std::copy(std::istream_iterator<int>(std::cin),
// std::istream_iterator<int>(),
// std::back_inserter(input));
}
四、C++20 Ranges 示例(革命性写法)
#include <ranges>
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {1, -2, 3, -4, 5};
// 链式操作:过滤正数 → 平方 → 取前3个
auto result = numbers
| std::views::filter([](int x) { return x > 0; })
| std::views::transform([](int x) { return x * x; })
| std::views::take(3);
for (int x : result) {
std::cout << x << " "; // 1 9 25
}
// 直接排序(无需 begin/end)
std::ranges::sort(numbers);
}
五、现代工具类示例
std::optional(C++17)
#include <optional>
#include <iostream>
std::optional<int> divide(int a, int b) {
if (b == 0) return std::nullopt;
return a / b;
}
int main() {
if (auto res = divide(10, 2)) {
std::cout << *res << "\n"; // 5
}
}
std::span(C++20)
#include <span>
#include <vector>
#include <iostream>
void print(std::span<const int> s) {
for (int x : s) std::cout << x << " ";
}
int main() {
std::vector<int> v = {1, 2, 3};
int arr[] = {4, 5, 6};
print(v); // OK
print(arr); // OK,自动转 span
}
std::print(C++23)
#include <print>
#include <vector>
int main() {
std::vector v = {1, 2, 3};
std::print("Vector: {}\n", v); // 输出:Vector: [1, 2, 3]
}
六、新旧写法对比
▶ 遍历 map
// C++98
for (std::map<std::string, int>::iterator it = m.begin(); it != m.end(); ++it)
std::cout << it->first << ": " << it->second << "\n";
// C++11
for (const auto& kv : m)
std::cout << kv.first << ": " << kv.second << "\n";
// C++17
for (const auto& [key, value] : m)
std::cout << key << ": " << value << "\n";
▶ 查找并处理
// C++98
std::vector<int>::iterator it = std::find(v.begin(), v.end(), 42);
if (it != v.end()) { /* ... */ }
// C++20 Ranges
if (auto it = std::ranges::find(v, 42); it != v.end()) { /* ... */ }
✅ 总结
| 组件 | 推荐写法(现代 C++) |
|---|---|
| 容器遍历 | for (const auto& x : c) |
| map 解包 | for (const auto& [k, v] : m) |
| 算法 | 优先用 std::ranges::xxx |
| 数组参数 | 用 std::span |
| 可能无值 | 用 std::optional |
| 输出容器 | C++23 用 std::print |
::::
| 误区 | 正确做法 |
|------|--------|
| “auto 会降低性能” | ❌ auto 是编译期推导,零运行时开销 |
| “智能指针很慢” | ❌ unique_ptr 无额外开销;shared_ptr 有原子计数,但通常可接受 |
| “STL 容器线程安全” | ❌ 所有 STL 容器都不是线程安全的!需手动加 mutex |
| “vector<bool> 是 vector” | ❌ 它是特化模板,行为像位集,避免使用,改用 vector<char> |
| “emplace_back 总比 push_back 快” | ❌ 仅当构造参数需转发且避免拷贝时才有优势 |