C++ Standard Library List
C++标准库列表
截至 C++26(2026 年 3 月已定稿),标准库的组件非常庞大。下面按功能类别整理了一份核心标准库组件表格,覆盖从 C++11 到 C++26 的主要头文件及其作用,并附上常见用法示例。
一、语言支持与基础工具
| 头文件 | 主要组件 | 作用 | 常见用法 |
|---|---|---|---|
<cstddef> | size_t, nullptr_t, byte | 基础类型定义 | size_t n = v.size(); |
<cstdint> | int32_t, uint64_t 等 | 固定宽度整数类型 | int32_t x = 42; |
<type_traits> | is_integral_v, enable_if_t | 编译期类型查询与变换 | static_assert(std::is_integral_v<int>); |
<concepts> | std::integral, std::floating_point | 概念库(C++20) | template<std::integral T> T sum(T a, T b); |
<coroutine> | coroutine_handle, suspend_always | 协程底层支持(C++20) | 配合 std::generator 使用 |
<source_location> | source_location::current() | 源码位置信息(C++20) | auto loc = std::source_location::current(); |
<version> | 特性测试宏 | 检查库实现状态(C++20) | #if __cpp_lib_generator >= 202207L |
<any> | std::any | 类型安全的任意值容器(C++17) | std::any a = 42; a = std::string("hi"); |
<optional> | std::optional<T> | 可能为空的值的封装(C++17) | std::optional<int> o = f(); if (o) use(*o); |
<variant> | std::variant<Ts...> | 类型安全的联合体(C++17) | std::variant<int,string> v = 1; |
<tuple> | std::tuple, std::get | 异构值集合 | auto t = std::make_tuple(1, "a"); |
<utility> | std::move, std::forward, std::pair | 移动语义与转发 | auto p = std::make_pair(1, 2); |
<bit> | std::bit_cast, std::popcount | 位操作(C++20) | auto n = std::popcount(0b1011u); |
<expected> | std::expected<T,E> | 值或错误的封装(C++23) | std::expected<int,string> r = parse(s); |
<print> | std::print, std::println | 格式化输出(C++23) | std::println("Hello, {}!", name); |
<format> | std::format | 类型安全格式化(C++20) | auto s = std::format("{:.2f}", 3.14); |
用法示例(std::expected) :
#include <expected>std::expected<double, std::string> parse_number(const std::string& s) { try { return std::stod(s); } catch (...) { return std::unexpected("invalid number"); }}auto r = parse_number("3.14");if (r) std::println("{}", *r);else std::println("Error: {}", r.error());std::expected 是 C++23 引入的标准错误处理方式,可以在不使用异常的情况下返回“值或错误”。
二、容器库
| 头文件 | 主要组件 | 作用 | 常见用法 |
|---|---|---|---|
<array> | std::array<T,N> | 固定大小数组(C++11) | std::array<int,3> a = {1,2,3}; |
<vector> | std::vector<T> | 动态数组 | std::vector<int> v{1,2,3}; v.push_back(4); |
<list> | std::list<T> | 双向链表 | std::list<int> l = {1,2,3}; l.push_front(0); |
<forward_list> | std::forward_list<T> | 单向链表(C++11) | std::forward_list<int> fl = {1,2,3}; |
<deque> | std::deque<T> | 双端队列 | std::deque<int> d; d.push_back(1); d.push_front(0); |
<map> | std::map<K,V> | 有序键值对(红黑树) | std::map<string,int> m; m["a"] = 1; |
<set> | std::set<T> | 有序唯一集合 | std::set<int> s = {3,1,2}; |
<unordered_map> | std::unordered_map<K,V> | 哈希键值对(C++11) | std::unordered_map<string,int> um; |
<unordered_set> | std::unordered_set<T> | 哈希集合(C++11) | std::unordered_set<int> us = {1,2,3}; |
<stack> | std::stack<T> | LIFO 栈适配器 | std::stack<int> st; st.push(1); |
<queue> | std::queue<T> | FIFO 队列适配器 | std::queue<int> q; q.push(1); |
<flat_map> | std::flat_map<K,V> | 连续内存映射(C++23) | std::flat_map<int,string> fm; fm[1]="a"; |
<flat_set> | std::flat_set<T> | 连续内存集合(C++23) | std::flat_set<int> fs = {3,1,2}; |
<inplace_vector> | std::inplace_vector<T,N> | 固定容量栈上向量(C++26) | std::inplace_vector<int,10> iv; iv.push_back(1); |
<hive> | std::hive<T> | 稳定地址容器(C++26) | 适合频繁插入删除、需地址稳定的场景 |
用法示例(std::vector + std::map) :
#include <vector>#include <map>#include <string>std::vector<int> v = {5, 2, 9, 1};v.push_back(6);for (const auto& x : v) std::print("{} ", x);std::map<std::string, int> scores;scores["Alice"] = 95;scores["Bob"] = 87;for (const auto& [name, score] : scores) std::println("{}: {}", name, score);vector 和 map 是 C++ 最常用的容器,分别适合动态数组和键值对场景。
C++23 新增容器说明:std::flat_map 和 std::flat_set 将元素存储在连续内存中,提供更好的缓存性能。C++26 的 std::inplace_vector 提供固定容量、栈上分配的序列,避免堆分配开销。
三、算法与迭代器
| 头文件 | 主要组件 | 作用 | 常见用法 |
|---|---|---|---|
<algorithm> | sort, find, count, transform | 通用算法 | std::sort(v.begin(), v.end()); |
<numeric> | accumulate, reduce, iota | 数值算法 | int s = std::accumulate(v.begin(), v.end(), 0); |
<ranges> | views::filter, views::transform, ranges::to | 范围库(C++20/23) | v | views::filter(pred) | views::take(5) |
<iterator> | begin, end, advance, next | 迭代器工具 | auto it = std::next(v.begin(), 2); |
<execution> | std::execution::par | 并行执行策略(C++17) | std::sort(std::execution::par, v.begin(), v.end()); |
用法示例(std::ranges + std::views) :
#include <ranges>#include <vector>std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};// 惰性视图:筛选偶数,取前3个,平方auto result = v | std::views::filter([](int n) { return n % 2 == 0; }) | std::views::take(3) | std::views::transform([](int n) { return n * n; });for (int x : result) std::print("{} ", x); // 4 16 36// C++23: ranges::to 将视图物化为容器auto vec = result | std::ranges::to<std::vector>();范围库让算法可以管道式组合,std::ranges::to(C++23)可将惰性视图直接转为具体容器。
四、内存管理
| 头文件 | 主要组件 | 作用 | 常见用法 |
|---|---|---|---|
<memory> | unique_ptr, shared_ptr, weak_ptr | 智能指针 | auto p = std::make_unique<Foo>(); |
<memory_resource> | pmr::vector, memory_resource | 多态分配器(C++17) | std::pmr::vector<int> v(&pool); |
<scoped_allocator> | scoped_allocator_adaptor | 嵌套分配器(C++11) | 容器嵌套时的分配器传播 |
智能指针对比:
| 智能指针 | 所有权 | 引用计数 | 适用场景 |
|---|---|---|---|
unique_ptr | 独占 | 无 | 独占资源,性能最优 |
shared_ptr | 共享 | 有 | 多对象共享同一资源 |
weak_ptr | 不拥有 | 不参与计数 | 观测共享对象、打破循环引用 |
// 独占所有权auto p = std::make_unique<Resource>();process(std::move(p));// 共享所有权auto shared = std::make_shared<Resource>();auto copy = shared; // 引用计数: 2// 弱引用(不增加计数)std::weak_ptr<Resource> weak = shared;if (auto locked = weak.lock()) { /* 使用 locked */ }智能指针是 RAII 原则在指针管理上的应用,自动管理资源生命周期,避免内存泄漏和悬空指针。
五、字符串与文本处理
| 头文件 | 主要组件 | 作用 | 常见用法 |
|---|---|---|---|
<string> | std::string, std::to_string | 动态字符串 | std::string s = "hello"; s += " world"; |
<string_view> | std::string_view | 非拥有字符串视图(C++17) | void f(std::string_view sv); |
<charconv> | std::from_chars, std::to_chars | 高效数字转换(C++17) | std::from_chars(s.data(), s.data()+s.size(), x); |
<format> | std::format | 格式化字符串(C++20) | std::format("{} = {:.2f}", name, val); |
<regex> | std::regex, std::smatch | 正则表达式(C++11) | std::regex re(R"(\d+)"); |
<text_encoding> | std::text_encoding | 编码检测(C++26) | 识别和转换字符编码 |
六、并发与并行
| 头文件 | 主要组件 | 作用 | 常见用法 |
|---|---|---|---|
<thread> | std::thread, std::jthread | 线程管理(jthread C++20) | std::jthread t([]{ work(); }); |
<mutex> | std::mutex, lock_guard, scoped_lock | 互斥量 | std::lock_guard lk(mtx); |
<atomic> | std::atomic<T> | 原子操作 | std::atomic<int> counter{0}; counter++; |
<condition_variable> | std::condition_variable | 条件变量 | cv.wait(lk, []{ return ready; }); |
<future> | std::future, std::promise, std::async | 异步任务 | auto f = std::async([]{ return 42; }); |
<barrier> | std::barrier | 线程屏障(C++20) | std::barrier sync(4); sync.arrive_and_wait(); |
<latch> | std::latch | 一次性倒计时(C++20) | std::latch l(4); l.count_down(); |
<semaphore> | std::counting_semaphore | 信号量(C++20) | std::counting_semaphore sem(3); |
<execution> | std::execution::sender/receiver | 统一异步框架(C++26) | 结构化并发,避免数据竞争 |
<simd> | std::simd | 数据并行(C++26) | 向量化运算 |
C++26 std::execution(Senders/Receivers) :这是 C++26 的旗舰并发特性,提供统一的异步执行框架。Senders 描述异步操作,Receivers 接收结果,通过 connect 连接后由 start 启动。
// 概念示意auto work = std::execution::just(42) | std::execution::then([](int x) { return x * 2; });auto [result] = std::this_thread::sync_wait(work).value();// result == 84该框架支持结构化并发,从构造上避免数据竞争和死锁。
七、数值计算
| 头文件 | 主要组件 | 作用 | 常见用法 |
|---|---|---|---|
<cmath> | std::sqrt, std::sin, std::pow | 数学函数 | double r = std::sqrt(2.0); |
<complex> | std::complex<T> | 复数类型 | std::complex<double> z(1, 2); |
<random> | std::mt19937, uniform_int_distribution | 随机数生成 | std::mt19937 gen{std::random_device{}()}; |
<ratio> | std::ratio<1,1000> | 编译期有理数(C++11) | using ms = std::ratio<1,1000>; |
<numbers> | std::numbers::pi | 数学常量(C++20) | double area = std::numbers::pi * r * r; |
<bit> | std::popcount, std::bit_width | 位操作(C++20) | auto n = std::popcount(x); |
<linalg> | std::linalg::dot, matrix_product | 基础线性代数(C++26) | BLAS 风格线性代数算法 |
// C++26 线性代数示例(概念示意)#include <linalg>#include <mdspan>// 基于 std::mdspan 的矩阵运算// std::linalg::matrix_product(A, B, C);八、输入/输出
| 头文件 | 主要组件 | 作用 | 常见用法 |
|---|---|---|---|
<iostream> | std::cin, std::cout, std::cerr | 标准流 I/O | std::cout << "Hello" << std::endl; |
<fstream> | std::ifstream, std::ofstream | 文件 I/O | std::ifstream f("data.txt"); |
<sstream> | std::stringstream, std::ostringstream | 字符串流 | std::ostringstream oss; oss << 42; |
<print> | std::print, std::println | 现代格式化输出(C++23) | std::println("x = {}, y = {}", x, y); |
<syncstream> | std::osyncstream | 线程安全输出(C++20) | std::osyncstream(std::cout) << "msg\n"; |
<span> | std::span<T> | 连续内存视图(C++20) | void f(std::span<int> data); |
<mdspan> | std::mdspan<T> | 多维数组视图(C++23) | 非拥有式多维数据访问 |
std::print / std::println(C++23) 提供了类似 Python 的格式化输出,相比 iostream 更简洁、类型安全、性能更好:
std::println("{} + {} = {}", 1, 2, 3);std::print("{:.3f}\n", 3.14159);九、C++23/26 重点新组件速览
| 组件 | 标准 | 作用 | 一句话用法 |
|---|---|---|---|
std::expected<T,E> | C++23 | 值或错误 | return std::unexpected("err"); |
std::generator<T> | C++23 | 协程生成器 | std::generator<int> gen() { co_yield 1; } |
std::print/println | C++23 | 格式化输出 | std::println("{}", x); |
std::flat_map/flat_set | C++23 | 连续内存容器 | 缓存友好替代 map/set |
std::mdspan | C++23 | 多维视图 | std::mdspan m(data, 3, 4); |
std::ranges::to | C++23 | 视图物化 | view | std::ranges::to<std::vector>() |
std::views::zip/enumerate | C++23 | 新范围适配器 | views::enumerate(v) |
import std; | C++23 | 模块化标准库 | import std; 替代所有头文件 |
std::inplace_vector | C++26 | 固定容量栈向量 | std::inplace_vector<int,10> iv; |
std::hive | C++26 | 稳定地址容器 | 频繁增删且需地址稳定 |
std::copyable_function | C++26 | std::function 替代 | 可复制的类型擦除可调用体 |
std::function_ref | C++26 | 轻量非拥有引用 | 替代 const std::function& 参数 |
std::execution | C++26 | 统一异步框架 | Sender/Receiver 结构化并发 |
std::linalg | C++26 | 线性代数 | 基于 mdspan 的 BLAS 风格算法 |
std::text_encoding | C++26 | 字符编码 | 编码检测与转换 |
std::optional<T&> | C++26 | 引用可选 | 支持引用类型的 optional |
std::simd | C++26 | 数据并行 | 显式向量化类型 |
std::generator(C++23)用法示例:
#include <generator>std::generator<int> fibonacci() { int a = 0, b = 1; while (true) { co_yield a; auto next = a + b; a = b; b = next; }}for (int x : fibonacci() | std::views::take(8)) std::print("{} ", x); // 0 1 1 2 3 5 8 13std::generator 是 C++23 引入的基于协程的惰性序列生成器,模型化 input_range,可直接用于范围 for 循环。
参考来源
以上内容综合了 cppreference 标准库头文件列表、C++23/26 新特性总结以及 C++26 定稿报道。由于 C++26 刚刚定稿,部分组件的编译器支持仍在完善中,建议在实际使用时关注所用编译器的版本和支持状态。
评论