编写 C++ 程序时,字符串拼接、动态数组与排序不必从零实现。这些能力由 C++ 标准库提供:声明位于各头文件,实现由标准库随编译器分发。教学章节已说明典型用法;本章按头文件列出高频接口,示例供对照查阅。

标准库包含哪些部分

C++ 标准库覆盖输入输出、字符串、容器、算法、智能指针、并发原语等。名称位于命名空间 std。使用某接口时须包含对应头文件,例如 #include <string> 后再写 std::string。

此外,标准库保留与 C 语言对应的头文件,如 <cstdio>、<cmath>。新代码优先使用 C++ 接口(std::string、std::vector),仅在对接 C API 时再使用 c_str() 或 C 风格函数。

为何使用标准库

  • 接口稳定:行为由标准约定,换编译器时语义保持一致。
  • 资源管理:容器与字符串按对象生命周期释放内存,减少手工 new / delete。
  • 与算法解耦:容器提供迭代器,<algorithm> 在区间上操作,不必为每种容器重写排序。

组合示例

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> words = {"vector", "string", "algorithm"};
    std::sort(words.begin(), words.end());
    for (const std::string& w : words) {
        std::cout << w << " ";
    }
    std::cout << std::endl;
    return 0;
}

输出:

algorithm string vector 

三个头文件各司其职:string 存文本,vector 存序列,sort 按字典序排列。教学说明见string、vector与STL 算法概览。

本批头文件

头文件用途
<string>std::string 文本:长度、查找、子串、C 风格转换
<vector>std::vector 动态数组:尾部增删、下标、容量调整
<algorithm>区间算法:排序、查找、计数、变换
<iostream>标准流:cin、cout、cerr 与常用格式化
<cmath>数学函数:开方、幂、取整、三角、反三角与双曲
<map>按键有序的键值对:find、at、insert
<set>有序去重集合
<numeric>累加、iota、内积
<utility>pair、swap、move
<memory>make_unique、make_shared
<sstream>在字符串上做流读写
<array>长度固定的数组
<stack>后进先出适配器
<queue>先进先出适配器
<iterator>begin、back_inserter、distance
<cctype>字符分类与大小写
<cstdlib>abs、atoi、strtol

查阅方式

头文件页给出函数总表;点击进入单页可看原型、参数、返回值与示例。函数页不出现在教程侧栏,以免条目过长。格式化操纵符声明于 <iomanip>,查阅时归在 iostream 一组;<cmath> 对应 C 语言的 math.h,名称位于 std。

本节给出标准库的定位与本批目录。下一节从<string>开始,按成员函数查阅文本操作。