C++ STL算法库提供高效通用函数,通过迭代器与容器解耦,支持多种容器操作。1. std::sort用于排序,默认升序,可配合greater或自定义比较函数实现降序;2. std::find执行线性查找,返回首个匹配元素迭代器,适用于无序数据;3. std::for_each遍历并执行操作,可结合函数或Lambda表达式使用;4. 其他常用算法包括std::count(计数)、std::binary_search(二分查找)、std::reverse(反转)、std::transform(变换)和std::copy(复制),均以迭代器为基础参数,提升代码效率与可读性。

C++ STL(标准模板库)中的算法库提供了一组高效、通用的函数,用于处理容器中的数据。这些算法通过迭代器与容器解耦,因此可以用于vector、list、array等多种容器类型。常用的算法包括sort(排序)、find(查找)、for_each(遍历执行)等。下面介绍它们的基本用法和常见技巧。
1. 排序:std::sort
std::sort 用于对容器中指定范围的元素进行排序,默认是升序排列。
基本语法:
std::sort(起始迭代器, 结束迭代器);示例:
立即学习“C++免费学习笔记(深入)”;
#include#include
#include iostream>
std::vector
std::sort(nums.begin(), nums.end()); // 升序
// 结果: {1, 2, 5, 8, 9}
std::sort(nums.begin(), nums.end(), std::greater
// 结果: {9, 8, 5, 2, 1}
也可以传入自定义比较函数:
bool cmp(int a, int b) {return a > b; // 降序
}
std::sort(nums.begin(), nums.end(), cmp);
2. 查找:std::find
std::find 在指定范围内查找某个值,返回第一个匹配元素的迭代器;若未找到,则返回结束迭代器。
#include#include
std::vector
auto it = std::find(nums.begin(), nums.end(), 30);
if (it != nums.end()) {
std::cout } else {
std::cout }
注意:find 是线性查找,时间复杂度为 O(n),适用于无序容器。如果容器已排序,可使用 binary_search 提高效率。
3. 遍历并操作:std::for_each
std::for_each 对范围内的每个元素执行指定操作,常用于打印、修改或调用函数。
#include#include
void print(int x) {
std::cout }
std::vector
std::for_each(nums.begin(), nums.end(), print); // 输出: 1 2 3 4
也可以使用 Lambda 表达式:
std::for_each(nums.begin(), nums.end(), [](int x) {std::cout }); // 输出: 2 4 6 8
4. 其他常用算法
STL 还提供了许多实用算法,以下是一些常见的:
- std::count:统计某值在范围中出现的次数
- std::binary_search:在有序序列中查找是否存在某值(返回 bool)
- std::reverse:反转容器中元素顺序
- std::transform:将范围内的元素通过函数转换后输出到另一位置
- std::copy:复制元素到另一个容器
示例:反转
std::reverse(nums.begin(), nums.end()); // 变成 {4, 3, 2, 1}基本上就这些。掌握这些 STL 算法能显著提升编码效率,避免手写循环和排序逻辑。关键是熟悉它们的参数形式——几乎都以“开始迭代器、结束迭代器”为基础,并可选地接收函数或谓词。多练习结合 vector、数组和 Lambda 使用,会越来越顺手。










