Z
ZHANK
模板与 STL

STL 算法

sort/find/count/transform/copy_if、lambda 配合算法

STL 算法

<algorithm> 提供了排序、查找、变换等 100+ 个算法——配合 lambda,写出的代码既短又清晰。

学完本章你将: 掌握 sort/find/count/transform/copy_if、lambda 配合算法。


排序与查找

cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};

    // 排序
    std::sort(v.begin(), v.end());           // 升序
    // 1 1 2 3 4 5 6 9

    std::sort(v.begin(), v.end(), std::greater<int>()); // 降序

    // 自定义排序
    std::sort(v.begin(), v.end(), [](int a, int b) {
        return a % 10 < b % 10;  // 按个位数排
    });

    // 查找
    auto it = std::find(v.begin(), v.end(), 5);
    if (it != v.end()) std::cout << "找到了 5\n";

    // 二分查找(必须先排序)
    bool found = std::binary_search(v.begin(), v.end(), 5);

    return 0;
}

统计与变换

cpp
// 计数
int n = std::count(v.begin(), v.end(), 1);  // 2
int m = std::count_if(v.begin(), v.end(),
    [](int x) { return x % 2 == 0; });      // 偶数的个数

// 变换
std::vector<int> doubled(v.size());
std::transform(v.begin(), v.end(), doubled.begin(),
    [](int x) { return x * 2; });

// 过滤拷贝
std::vector<int> evens;
std::copy_if(v.begin(), v.end(), std::back_inserter(evens),
    [](int x) { return x % 2 == 0; });

常用算法速查

算法作用
sort排序
find / find_if查找
count / count_if计数
transform变换
copy / copy_if拷贝
remove_if移除(配合 erase)
for_each遍历执行
accumulate累加(在 `` 中)
max_element / min_element找最值