Skip to content

STL 六大组件与迭代器

STL 不是一堆容器的合集,是一套泛型编程框架:容器管数据、迭代器管遍历、算法管操作、函数对象管策略、适配器管转换、分配器管内存。六个组件靠「迭代器」这个抽象粘合在一起——算法不知道自己在遍历 vector 还是 list,它只跟迭代器打交道。理解这个分层,STL 就从「背 API」变成「会组合」。

一、六大组件总览

┌─────────────────────────────────────────────┐
│  算法 Algorithms(sort/find/transform...)    │  ← 不碰容器,只吃迭代器
├─────────────────────────────────────────────┤
│  函数对象 Function Objects(谓词/比较器)      │  ← 算法的「策略」参数
├──────────┬──────────┬───────────────────────┤
│ 顺序容器  │ 关联容器  │ 无序关联容器           │  ← 数据的组织方式
├──────────┴──────────┴───────────────────────┤
│  迭代器 Iterators                            │  ← 统一的遍历抽象
├─────────────────────────────────────────────┤
│  适配器 Adapters(stack/queue/inserter)     │  ← 改造接口
├─────────────────────────────────────────────┤
│  分配器 Allocators                           │  ← 内存的来源(通常不用关心)
└─────────────────────────────────────────────┘

分层的意义:std::find 一份代码能遍历 vector、list、数组、map,因为它只依赖迭代器接口。这就是泛型——用模板把「数据结构」和「算法」解耦。

二、容器分类体系

大类成员特点
顺序容器vector deque list forward_list array元素位置由插入顺序决定,可用下标
关联容器set map multiset multimap有序(红黑树),按键查找 O(log n)
无序关联容器unordered_set unordered_map 及 multi 版(C++11)哈希表,平均 O(1)
容器适配器stack queue priority_queue基于其他容器的接口封装
字符串string顺序容器的特化(只存 char)

各容器的用法与复杂度详见《STL 容器详解与实现原理》。本篇建立框架认知。

三、迭代器

3.1 什么是迭代器

迭代器是「行为像指针的对象」:*it 取元素、++it 前进、it != end 判断。所有容器都提供 begin()/end(),所有算法都吃迭代器区间:

cpp
std::vector<int> v{3, 1, 4, 1, 5};
std::sort(v.begin(), v.end());        // 左闭右开:[begin, end)
auto it = std::find(v.begin(), v.end(), 4);

区间约定 [first, last):last 指向最后一个元素的下一格。这个设计让空区间表示为 first == last,遍历条件统一为 it != last——C/C++ 一切范围遍历(指针、迭代器)都遵守它。

3.2 五类迭代器(能力分级)

类别能力容器
输入迭代器只读,单遍,只能 ++istream_iterator
输出迭代器只写,单遍,只能 ++ostream_iterator、back_inserter
前向迭代器读写,多遍,只能 ++forward_list、无序容器
双向迭代器以上 + --list、set/map
随机访问迭代器以上 + it + n、it[n]、比较大小vector、deque、array、string

能力分层决定了算法适用范围:std::sort 要随机访问(所以 list 不能 sort 算法,要用成员 sort),std::find 只要前向。给自定义容器写迭代器时,用 iterator_traits 声明能力,算法才能正确选型。

3.3 常用成员类型别名

cpp
std::vector<int>::iterator it;              // 读写迭代器
std::vector<int>::const_iterator cit;       // 只读迭代器
std::vector<int>::reverse_iterator rit;     // 反向迭代器(++ 往前跑)
std::vector<int>::difference_type d;        // 两个迭代器距离,有符号
std::vector<int>::size_type n;              // 无符号大小

C++11 起用 auto + cbegin()/cend() 少写一半类型:

cpp
for (auto it = v.cbegin(); it != v.cend(); ++it) { }
for (auto it = v.rbegin(); it != v.rend(); ++it) { }    // 逆序遍历

3.4 插入迭代器(适配器)

普通迭代器不能「边遍历边插入」——插入会让迭代器失效。插入迭代器把赋值操作转成插入:

cpp
std::vector<int> src{1, 2, 3};
std::vector<int> dst;
std::copy(src.begin(), src.end(), std::back_inserter(dst));   // 赋值即 push_back

std::list<int> l;
std::copy(src.begin(), src.end(), std::front_inserter(l));    // 赋值即 push_front(逆序)

std::set<int> s;
std::copy(src.begin(), src.end(), std::inserter(s, s.begin()));  // 赋值即 insert

四、算法与区间

算法的调用形式统一为:

cpp
算法(区间起点, 区间终点, [参数...])

这个「区间 + 策略」的模式贯穿整个 STL。算法大致分七族(详见《STL 算法与数据操作》):非变易算法(find/count/for_each)、变易算法(copy/replace/remove)、排序(sort/nth_element)、二分查找(lower_bound)、数值(accumulate)、集合(set_union)、其他(min/max/swap)。

算法只操作迭代器,所以同一个算法能作用于数组:

cpp
int arr[] = {5, 3, 1, 4};
std::sort(arr, arr + 4);              // 原生数组 + 指针就是合法迭代器

五、函数对象与谓词

5.1 函数对象(仿函数)

重载了 operator() 的对象就是函数对象——可以像函数一样调用,且能携带状态:

cpp
struct MultiplyBy {
    int factor;
    int operator()(int x) const { return x * factor; }   // 有状态!
};
MultiplyBy times3{3};
times3(10);       // 30

比函数指针强的地方:能内联(编译器知道具体类型)、能带状态、能作模板参数。

5.2 内建函数对象(<functional>)

标准库提供一批现成仿函数:

类别成员
算术plus minus multiplies divides modulus negate
比较equal_to not_equal_to greater less greater_equal less_equal
逻辑logical_and logical_or logical_not
位运算bit_and bit_or bit_xor

用法:

cpp
std::sort(v.begin(), v.end(), std::greater<int>{});    // 降序
int total = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>{});  // 连乘

5.3 谓词

谓词是返回 bool 的可调用实体,给算法当「条件」:

  • 一元谓词(find_if/remove_if/count_if):判断单个元素。
  • 二元谓词(sort/unique/set 容器):比较两个元素。
cpp
bool is_even(int x) { return x % 2 == 0; }

auto first_even = std::find_if(v.begin(), v.end(), is_even);
auto n = std::count_if(v.begin(), v.end(), is_even);
v.erase(std::remove_if(v.begin(), v.end(), is_even), v.end());   // erase-remove 惯用法

C++11 起谓词的主力是 lambda(语法见现代 C++ 篇):

cpp
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });   // 降序
std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });

比较器必须满足严格弱序:comp(a,a) 为假(非自反)、传递、不可比元素间等价。写 <= 当比较器是经典错误——sort 会越界访问或死循环:

cpp
std::sort(v.begin(), v.end(), [](int a, int b) { return a <= b; });   // 错误!必须用 <

六、适配器

适配器给现有组件「换接口」,不改实现:

种类例子作用
容器适配器stack queue priority_queue把 deque/vector/list 包成栈/队列/堆
迭代器适配器back_inserter reverse_iterator istream_iterator改迭代器行为
函数适配器bind/placeholders(C++11 前主流)、not_fn(C++17)改造可调用对象
C++20 ranges 适配器views::filter views::transform views::take惰性视图

std::bind 固定部分参数:

cpp
auto add = [](int a, int b) { return a + b; };
auto plus10 = std::bind(add, 10, std::placeholders::_1);   // 固定第一个参数
plus10(5);      // 15

现代代码里 bind 基本被 lambda 取代——auto plus10 = [](int b) { return add(10, b); }; 更直白。bind 的坑(参数拷贝时机、占位符顺序、对重载的歧义)也让它的性价比很低。

七、通用工具

7.1 pair 与 tuple

cpp
#include <utility>
std::pair<int, std::string> p{1, "one"};
p.first; p.second;
auto q = std::make_pair(2, "two");       // 类型推导

#include <tuple>
std::tuple<int, double, std::string> t{1, 3.14, "x"};
std::get<0>(t); std::get<2>(t);
auto [a, b, c] = t;                      // C++17 结构化绑定解包
std::get<int>(t);                        // 按类型取(C++14,类型唯一时)

map 的 insert/emplace 返回 pair<iterator, bool>,*it 解出来是 pair<const Key, Value>——这是 pair 最高频的出场方式。

7.2 swap / move / forward

cpp
std::swap(a, b);                  // 交换:vector 是指针交换 O(1),内置类型是三次拷贝
std::move(a);                     // 把 a 「变成右值」——宣布「我的资源可以拿走」
std::forward<T>(t);               // 保持参数的值类别转发(模板篇详解)

std::swap 对标准容器有重载,走移动语义所以是 O(1)。std::move 不移动任何东西,它只是个 static_cast<T&&>——真正的移动发生在接收右值的构造函数/赋值函数里。

7.3 迭代器工具

cpp
std::next(it, 2);                 // 返回 it 后移 2 位的迭代器,it 不动
std::prev(it);                    // 前移一位
std::distance(first, last);       // 元素个数(随机访问 O(1),其余 O(n))
auto [mn, mx] = std::minmax_element(v.begin(), v.end());   // C++11:一次遍历取最大最小

八、分配器(先知道有这回事)

每个容器都有 Allocator 模板参数,默认 std::allocator<T>——封装 operator new/delete。日常使用无感,需要时(内存池、共享内存、调试分配)可以替换:

cpp
std::vector<int, MyPoolAllocator<int>> v;    // 用池分配器的 vector

C++17 的多态分配器(std::pmr::vector 等)让运行期切换分配策略成为可能,实战细节见《异常处理与内存管理》。

九、选型速查

需求选择
默认序列容器vector
头尾都要高效插入deque
中间频繁插入删除、迭代器要稳定list
只存单链表、内存紧forward_list
编译期定长array
按键查找、有序遍历map/set
不关心顺序、只要快unordered_map/unordered_set
LIFOstack
FIFOqueue
带优先级priority_queue
字符串string(只读视图 string_view,C++17)

相关阅读

  • 《STL 容器详解与实现原理》—— 逐个容器的用法与内部结构
  • 《STL 算法与数据操作》—— 算法全谱与实战
  • 《模板与泛型编程》—— STL 背后的语言机制

CTO Plus技术栈 Version 1.0.20261024-12