Skip to content

STL 算法与数据操作

算法是 STL 的引擎:一百多个函数,全部遵循「区间 + 谓词」的统一形式,全部基于迭代器工作。这篇按使用频率组织——排序、查找、变易、数值四大族各给代表算法和复杂度,然后讲迭代器适配器(back_inserter 等)、异常安全保证,最后落到实战:词频统计、TopK、分组聚合这些每天要写的数据操作。

一、算法版图

头文件家族代表
<algorithm>非变易find count all_of for_each min_element
<algorithm>变易copy remove replace transform unique reverse fill sort
<algorithm>二分查找lower_bound upper_bound binary_search equal_range
<algorithm>集合set_union set_intersection merge includes
<numeric>数值accumulate iota reduce gcd lcm partial_sum
<execution>(C++17)并行策略std::execution::par 等

调用形式永远一样:

cpp
std::algorithm(first, last, ...);

先排序再二分:lower_bound/binary_search 要求区间已按同一比较器排序,未排序区间上结果是垃圾。

二、排序族

2.1 sort / stable_sort

cpp
std::vector<int> v{5, 2, 8, 1, 9, 2};
std::sort(v.begin(), v.end());                       // 升序,O(n log n)
std::sort(v.begin(), v.end(), std::greater<int>{});  // 降序
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
  • std::sort:内省排序(快排 + 堆排 + 插入排序混合),不稳定——相等元素的相对顺序可能变。默认底层是 introsort:快排主体、递归过深退化堆排(防最坏 O(n²))、小区间切插入排序。
  • std::stable_sort:归并排序,稳定,相等元素保持原相对顺序;需要额外内存,慢一些。

什么时候必须 stable:按分数排序学生,同分要保持原名单顺序;多轮排序(先按 A 排再按 B 排)时后一轮要稳定。其他情况 sort 就够。

cpp
// 按长度排序字符串,同长度按字典序——单次比较器搞定,不需要 stable
std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) {
    return a.size() != b.size() ? a.size() < b.size() : a < b;
});

2.2 partial_sort / nth_element

cpp
std::vector<int> v(1000);
std::iota(v.begin(), v.end(), 0);
std::random_shuffle(v.begin(), v.end());   // C++14 起弃用,改用 std::shuffle + 随机引擎

std::partial_sort(v.begin(), v.begin() + 10, v.end());   // 前 10 小有序,其余无序,O(n log k)
std::nth_element(v.begin(), v.begin() + 10, v.end());    // 保证第 10 小在对的位置,O(n) 平均

TopK 场景的对应选择:只要前 K 个有序 → partial_sort;只要第 K 大/小的值或把它当分界 → nth_element(更快)。K 很小且数据量大时优先考虑 priority_queue。

2.3 比较器的严格弱序

sort 的比较器必须定义严格弱序:comp(a,a) 必须为假(不满足就是逻辑错误);comp(a,b) 且 comp(b,c) ⇒ comp(a,c)(传递);不可比的元素视为等价。

cpp
// 错误:用 <= 当比较器,相等时 comp(a,a) 为真 → 未定义行为(可能死循环或越界)
std::sort(v.begin(), v.end(), [](int a, int b) { return a <= b; });

// 错误:先按 a.x 后按 a.y,但 a.x 相等时又比较了 b——非传递
std::sort(v.begin(), v.end(), [](const P& a, const P& b) {
    if (a.x == b.x) return a.y < b.y;
    return a.x < b.x;
});   // 这个其实是对的。真正错误的是下面这种「和基准比」的:

对 std::string 排序默认字典序;对自定义类型,实现 operator<(C++20 用 <=>)比每次手写 lambda 省事。

三、查找族

3.1 线性查找

cpp
auto it = std::find(v.begin(), v.end(), 42);               // 值查找,O(n)
auto it2 = std::find_if(v.begin(), v.end(), pred);         // 条件查找
int n = std::count(v.begin(), v.end(), 42);                // 计数
bool any = std::any_of(v.begin(), v.end(), pred);          // 存在
bool all = std::all_of(v.begin(), v.end(), pred);          // 全部
bool none = std::none_of(v.begin(), v.end(), pred);        // 一个都没有

C++20 起 <algorithm> 提供 ranges 版本:std::ranges::find(v, 42)——不用传 begin/end,直接传容器,还能管道组合。

3.2 二分查找(要求有序)

cpp
std::vector<int> sorted{1, 3, 3, 5, 7, 9};

bool found = std::binary_search(sorted.begin(), sorted.end(), 5);     // 只答「在不在」,O(log n)

auto lo = std::lower_bound(sorted.begin(), sorted.end(), 3);          // 第一个 >= 3
auto hi = std::upper_bound(sorted.begin(), sorted.end(), 3);          // 第一个 > 3
auto [first, last] = std::equal_range(sorted.begin(), sorted.end(), 3);  // 值 3 的区间
int count3 = std::distance(lo, hi);                                    // 2

// 自定义类型同样适用
auto it = std::lower_bound(people.begin(), people.end(), 30,
    [](const Person& p, int age) { return p.age < age; });   // 第一个 age >= 30

四个函数的返回值分工是面试高频也是实战高频:

函数返回
binary_searchbool,不告诉你位置
lower_bound第一个不小于目标的位置
upper_bound第一个大于目标的位置
equal_range上述两者组成的 pair

注意 binary_search 用 lower_bound 实现,判断靠「位置有效 + 值相等」——它对比较器的要求和排序一致。

四、变易算法

4.1 copy / transform

cpp
std::vector<int> src{1, 2, 3}, dst(3);
std::copy(src.begin(), src.end(), dst.begin());        // 拷贝,返回目标区间末尾

std::vector<int> squared(src.size());
std::transform(src.begin(), src.end(), squared.begin(), [](int x) { return x * x; });

// 双输入版本:合并两个序列
std::transform(a.begin(), a.end(), b.begin(), result.begin(),
               [](int x, int y) { return x + y; });

4.2 remove 家族与 erase-remove 惯用法

remove 不删元素——它把「要保留的」搬到前面,返回新逻辑末尾,后面的元素变成废弃值:

cpp
std::vector<int> v{1, 2, 3, 2, 4};
auto new_end = std::remove(v.begin(), v.end(), 2);    // 逻辑删:前 3 个是 1 3 4
// v 现在是 {1, 3, 4, ?, ?},size 仍 5
v.erase(new_end, v.end());                            // 物理删:真正缩小到 3

标准写法压成一行——erase-remove 惯用法:

cpp
v.erase(std::remove(v.begin(), v.end(), 2), v.end());
v.erase(std::remove_if(v.begin(), v.end(), is_even), v.end());

std::erase/std::erase_if(C++20)给容器加了成员级封装,一行就够:std::erase(v, 2)。

4.3 unique / reverse / fill

cpp
std::vector<int> v{1, 1, 2, 3, 3, 3, 4};
v.erase(std::unique(v.begin(), v.end()), v.end());    // 去「相邻」重复:先 sort 再 unique 才彻底

std::reverse(v.begin(), v.end());                     // 原地反转
std::fill(v.begin(), v.end(), 0);                     // 全部填 0
std::iota(v.begin(), v.end(), 100);                    // <numeric>:填 100, 101, 102...

unique 只去相邻重复——很多人忘了先 sort,结果重复值还在。

五、数值算法(<numeric>)

cpp
#include <numeric>
std::vector<int> v{1, 2, 3, 4, 5};

int sum = std::accumulate(v.begin(), v.end(), 0);                    // 15
int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>{});  // 120
std::string joined = std::accumulate(v.begin(), v.end(), std::string{},
    [](std::string acc, int x) { return acc += std::to_string(x); });   // 字符串拼接

std::vector<int> prefix(v.size());
std::partial_sum(v.begin(), v.end(), prefix.begin());    // 前缀和:1 3 6 10 15
std::adjacent_difference(v.begin(), v.end(), diff.begin());  // 相邻差

int total = std::reduce(v.begin(), v.end());             // C++17:accumulate 的并行版
std::gcd(12, 18); std::lcm(4, 6);                       // C++17:最大公约数/最小公倍数

accumulate 的第三个参数是初值,它决定返回类型:0 得 int,0.0 得 double,std::string{} 得字符串。类型给错会默默截断:

cpp
double avg = std::accumulate(v.begin(), v.end(), 0) / v.size();   // 错误:整除
double avg2 = std::accumulate(v.begin(), v.end(), 0.0) / v.size();  // 正确

六、集合算法

对两个升序区间做交并差:

cpp
std::vector<int> a{1, 2, 3, 5}, b{2, 4, 5, 6}, out(8);

auto end = std::set_union(a.begin(), a.end(), b.begin(), b.end(), out.begin());          // 1 2 3 4 5 6
auto end2 = std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), out.begin()); // 2 5
auto end3 = std::set_difference(a.begin(), a.end(), b.begin(), b.end(), out.begin());   // 1 3
bool sub = std::includes(a.begin(), a.end(), b.begin(), b.end());   // b ⊆ a?

输出位置要预留足够空间(a.size() + b.size() 是并集上限),或配合 back_inserter。元素类型只要求 operator<。

七、迭代器适配器深入

7.1 插入迭代器

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

*it = value 被实现为 container->push_back(value),所以 std::copy 这种「赋值到目标区间」的算法可以边算边插入。

7.2 流迭代器

cpp
#include <iterator>
std::istream_iterator<int> in(std::cin), eof;
std::vector<int> v(in, eof);          // 从 cin 读 int 直到 EOF/非数字

std::ostream_iterator<int> out(std::cout, " ");
std::copy(v.begin(), v.end(), out);   // 打印,元素间插空格

读文件、写日志的极简写法,注意输入失败时迭代器自动等于 eof。

7.3 反向迭代器

cpp
for (auto it = v.rbegin(); it != v.rend(); ++it) { }   // 逆序访问
std::sort(v.rbegin(), v.rend());                       // 降序排序的技巧写法

rbegin() 对应 end(),++ 往前走——把「正序算法」反过来用的经典技巧。

八、异常安全保证

STL 算法按异常安全分三档:

保证含义例子
基本保证抛出异常时不泄漏资源,对象处于合法状态大多数算法
强保证要么完全成功,要么状态回到调用前vector::insert(扩容失败时旧数据完好)、vector::push_back
不抛保证(noexcept)不抛异常swap(容器版,移动指针)

push_back 的强保证是这样实现的:先分配新内存并移动/拷贝元素,成功后才释放旧内存——分配失败抛 bad_alloc 时,原 vector 分毫未动。自己写容器也要按这个节奏:先备好退路,再动现有状态。

erase-remove 惯用法天然安全:remove 是纯搬移不抛异常,erase 只释放,抛也只可能来自元素析构——那是调用方的责任。

九、实战:基于 STL 的数据分析

9.1 词频统计 TopK

cpp
#include <algorithm>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>

std::vector<std::pair<std::string, int>> top_k_words(
        const std::string& text, size_t k) {
    std::istringstream iss(text);
    std::map<std::string, int> freq;
    std::string word;
    while (iss >> word) {
        ++freq[word];                       // map 自动建项,从 0 开始 ++
    }

    std::vector<std::pair<std::string, int>> items(freq.begin(), freq.end());
    // 按频次降序;同频次按字典序——比较器一次搞定
    std::partial_sort(items.begin(), items.begin() + std::min(k, items.size()),
                      items.end(),
                      [](const auto& a, const auto& b) {
                          return a.second != b.second ? a.second > b.second
                                                      : a.first < b.first;
                      });
    items.resize(std::min(k, items.size()));
    return items;
}

需要更快(不在乎顺序)时把 map 换成 unordered_map,统计阶段从 O(n log n) 降到 O(n)。

9.2 分组聚合

cpp
struct Sale { std::string region; double amount; };
std::vector<Sale> sales{{"east", 100}, {"west", 200}, {"east", 150}};

std::map<std::string, double> by_region;
for (const auto& s : sales) {
    by_region[s.region] += s.amount;       // 分组求和的标准写法
}
// by_region: east=250, west=200

9.3 数据清洗模板

cpp
// 去掉空串、trim、去重、排序——链式 erase 惯用法
data.erase(std::remove_if(data.begin(), data.end(),
                          [](const std::string& s) { return s.empty(); }),
           data.end());
std::sort(data.begin(), data.end());
data.erase(std::unique(data.begin(), data.end()), data.end());

十、用 STL 实现常见数据结构

10.1 栈与队列

直接用 stack/queue 适配器即可(用法见容器篇)。注意栈顶判空、队列的 front 语义。

10.2 优先队列/堆

cpp
std::priority_queue<int> max_heap(v.begin(), v.end());   // 建堆 O(n),v 变堆
max_heap.top(); max_heap.pop();

10.3 图:邻接表

cpp
using Graph = std::vector<std::vector<std::pair<int, int>>>;   // 点 → (邻居, 权重)

Graph g(5);
g[0].emplace_back(1, 10);      // 0 → 1,权重 10
g[0].emplace_back(2, 3);
g[1].emplace_back(2, 1);

// BFS
std::vector<bool> visited(g.size(), false);
std::queue<int> q;
q.push(0);
visited[0] = true;
while (!q.empty()) {
    int u = q.front(); q.pop();
    for (auto [v, w] : g[u]) {
        if (!visited[v]) { visited[v] = true; q.push(v); }
    }
}

10.4 并查集(DSU)

cpp
class DSU {
public:
    explicit DSU(size_t n) : parent_(n), rank_(n, 0) {
        std::iota(parent_.begin(), parent_.end(), 0);   // 自己是自己的根
    }
    int find(int x) {
        while (parent_[x] != x) {
            parent_[x] = parent_[parent_[x]];    // 路径压缩(减半)
            x = parent_[x];
        }
        return x;
    }
    void unite(int a, int b) {
        a = find(a); b = find(b);
        if (a == b) return;
        if (rank_[a] < rank_[b]) std::swap(a, b);   // 按秩合并
        parent_[b] = a;
        if (rank_[a] == rank_[b]) ++rank_[a];
    }
    bool connected(int a, int b) { return find(a) == find(b); }
private:
    std::vector<int> parent_, rank_;
};

接近 O(1) 摊还的连通性查询,Kruskal 最小生成树、判断成环的标准工具。

10.5 LRU

完整实现见《C++ 实战:手写类与经典案例》,核心就是 unordered_map + list 的分工:map 管 O(1) 查找,list 管 O(1) 调整顺序。

十一、STL 与多线程的整合

STL 容器不是线程安全的——这是最常见的误解。「线程安全」要分两层看:

  • 只读共享是安全的:多个线程同时遍历同一个 vector,不做任何修改,没问题。
  • 一写多读、多写都需要外部同步:两个线程同时 push_back 同一个 vector 是数据竞争,UB。哪怕看起来「各自 push 不同的东西」。

标准做法:加锁保护容器,或按线程分容器最后合并,或用线程安全队列(mutex + condition_variable 包装,或第三方库如 moodycamel::ConcurrentQueue)。注意 vector 扩容和 unordered_map 重哈希会让迭代器/引用失效——多线程场景这比崩溃更难查。

STL 和并发的正确结合点:

cpp
// 并行算法(C++17):库内部切分,你保证元素间无依赖
std::sort(std::execution::par, v.begin(), v.end());
std::for_each(std::execution::par_unseq, items.begin(), items.end(),
              [](auto& x) { process(x); });

相关阅读

  • 《STL 容器详解与实现原理》—— 容器的复杂度与失效规则
  • 《STL 六大组件与迭代器》—— 迭代器与函数对象理论
  • 《多线程与并发编程》—— 并行算法与同步原语

CTO Plus技术栈 Version 1.0.20261024-12