当前位置: 首页 > news >正文

C++ 标准库中的 <algorithm> 头文件算法总结

C++ 常用 <algorithm> 算法概览

  C++ 标准库中的 <algorithm> 头文件提供了大量有用的算法,主要用于操作容器(如 vector, list, array 等)。这些算法通常通过迭代器来操作容器元素。

1. 非修改序列操作

std::all_of, std::any_of, std::none_of

#include <algorithm>
#include <vector>

std::vector<int> v = {1, 2, 3, 4, 5};

// 检查所有元素是否满足条件
bool all_even = std::all_of(v.begin(), v.end(), [](int i){ return i % 2 == 0; });

// 检查是否有任一元素满足条件
bool any_even = std::any_of(v.begin(), v.end(), [](int i){ return i % 2 == 0; });

// 检查是否没有元素满足条件
bool none_even = std::none_of(v.begin(), v.end(), [](int i){ return i % 2 == 0; });

std::for_each

std::vector<int> v = {1, 2, 3, 4, 5};

// 对每个元素执行操作
std::for_each(v.begin(), v.end(), [](int &n){ n *= 2; });

std::count, std::count_if

std::vector<int> v = {1, 2, 3, 4, 5};

// 计算等于3的元素个数
int count_3 = std::count(v.begin(), v.end(), 3);

// 计算满足条件的元素个数
int count_even = std::count_if(v.begin(), v.end(), [](int i){ return i % 2 == 0; });

std::find, std::find_if, std::find_if_not

std::vector<int> v = {1, 2, 3, 4, 5};

// 查找值为3的元素
auto it = std::find(v.begin(), v.end(), 3);

// 查找第一个偶数
auto it_even = std::find_if(v.begin(), v.end(), [](int i){ return i % 2 == 0; });

// 查找第一个非偶数
auto it_not_even = std::find_if_not(v.begin(), v.end(), [](int i){ return i % 2 == 0; });

2. 修改序列操作

std::copy, std::copy_if

std::vector<int> src = {1, 2, 3, 4, 5};
std::vector<int> dst(5);

// 复制元素
std::copy(src.begin(), src.end(), dst.begin());

// 条件复制
std::vector<int> dst_even;
std::copy_if(src.begin(), src.end(), std::back_inserter(dst_even), 
             [](int i){ return i % 2 == 0; });

std::fill, std::fill_n

std::vector<int> v(5);

// 填充所有元素为42
std::fill(v.begin(), v.end(), 42);

// 填充前3个元素为10
std::fill_n(v.begin(), 3, 10);

std::transform

std::vector<int> v = {1, 2, 3, 4, 5};
std::vector<int> result(v.size());

// 对每个元素应用函数
std::transform(v.begin(), v.end(), result.begin(), 
               [](int i){ return i * 2; });

std::replace, std::replace_if

std::vector<int> v = {1, 2, 3, 4, 5};

// 替换所有3为10
std::replace(v.begin(), v.end(), 3, 10);

// 替换所有偶数为0
std::replace_if(v.begin(), v.end(), 
                [](int i){ return i % 2 == 0; }, 0);

std::remove, std::remove_if

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

// "移除"所有3(实际上是移动到最后,返回新的逻辑end)
auto new_end = std::remove(v.begin(), v.end(), 3);
v.erase(new_end, v.end()); // 真正删除

// "移除"所有偶数
new_end = std::remove_if(v.begin(), v.end(), [](int i){ return i % 2 == 0; });
v.erase(new_end, v.end());

3. 排序和相关操作

std::sort, std::stable_sort

std::vector<int> v = {5, 3, 1, 4, 2};

// 默认升序排序
std::sort(v.begin(), v.end());

// 自定义排序
std::sort(v.begin(), v.end(), [](int a, int b){ return a > b; }); // 降序

// 稳定排序(保持相等元素的相对顺序)
std::stable_sort(v.begin(), v.end());

std::partial_sort

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

// 部分排序(前3个最小的元素)
std::partial_sort(v.begin(), v.begin() + 3, v.end());

std::nth_element

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

// 使第n个元素处于正确位置
std::nth_element(v.begin(), v.begin() + 2, v.end());
// v[2]现在是排序后的正确元素,前面的都<=它,后面的都>=它

std::is_sorted, std::is_sorted_until

std::vector<int> v = {1, 2, 3, 4, 5};

// 检查是否已排序
bool sorted = std::is_sorted(v.begin(), v.end());

// 查找第一个破坏排序的元素
auto it = std::is_sorted_until(v.begin(), v.end());

4. 二分搜索(必须在已排序的序列上使用)

std::lower_bound, std::upper_bound, std::equal_range

std::vector<int> v = {1, 2, 2, 3, 4, 5};

// 查找第一个不小于3的元素
auto low = std::lower_bound(v.begin(), v.end(), 3);

// 查找第一个大于3的元素
auto up = std::upper_bound(v.begin(), v.end(), 3);

// 查找等于3的范围
auto range = std::equal_range(v.begin(), v.end(), 3);

std::binary_search

std::vector<int> v = {1, 2, 3, 4, 5};

// 检查元素是否存在
bool found = std::binary_search(v.begin(), v.end(), 3);

5. 集合操作(必须在已排序的序列上使用)

std::merge

std::vector<int> v1 = {1, 3, 5};
std::vector<int> v2 = {2, 4, 6};
std::vector<int> dst(v1.size() + v2.size());

// 合并两个已排序的序列
std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), dst.begin());

std::includes, std::set_difference, std::set_intersection, std::set_union, std::set_symmetric_difference

std::vector<int> v1 = {1, 2, 3, 4, 5};
std::vector<int> v2 = {2, 4, 6};

std::vector<int> result;

// 检查v1是否包含v2的所有元素
bool includes = std::includes(v1.begin(), v1.end(), v2.begin(), v2.end());

// 差集(v1 - v2)
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), 
                   std::back_inserter(result));

// 交集
result.clear();
std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(),
                     std::back_inserter(result));

// 并集
result.clear();
std::set_union(v1.begin(), v1.end(), v2.begin(), v2.end(),
              std::back_inserter(result));

// 对称差集(在v1或v2中但不同时在两者中)
result.clear();
std::set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(),
                            std::back_inserter(result));

6. 堆操作

std::make_heap, std::push_heap, std::pop_heap, std::sort_heap

std::vector<int> v = {3, 1, 4, 1, 5, 9};

// 构建最大堆
std::make_heap(v.begin(), v.end());

// 添加元素到堆
v.push_back(6);
std::push_heap(v.begin(), v.end());

// 移除堆顶元素
std::pop_heap(v.begin(), v.end());
v.pop_back();

// 堆排序
std::sort_heap(v.begin(), v.end());

7. 最小/最大值操作

std::min_element, std::max_element, std::minmax_element

std::vector<int> v = {3, 1, 4, 1, 5, 9};

// 查找最小元素
auto min_it = std::min_element(v.begin(), v.end());

// 查找最大元素
auto max_it = std::max_element(v.begin(), v.end());

// 同时查找最小和最大元素
auto minmax = std::minmax_element(v.begin(), v.end());

std::clamp (C++17)

int value = 15;
// 将值限制在10-20范围内
int clamped = std::clamp(value, 10, 20); // 返回15
clamped = std::clamp(5, 10, 20); // 返回10
clamped = std::clamp(25, 10, 20); // 返回20

8. 排列操作

std::next_permutation, std::prev_permutation

std::vector<int> v = {1, 2, 3};

// 生成下一个排列
do {
    // 处理当前排列
} while (std::next_permutation(v.begin(), v.end()));

// 生成前一个排列
std::prev_permutation(v.begin(), v.end());

9. 其他有用算法

std::accumulate (来自 <numeric>)

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

// 求和
int sum = std::accumulate(v.begin(), v.end(), 0);

// 自定义操作(如乘积)
int product = std::accumulate(v.begin(), v.end(), 1, 
                             [](int a, int b){ return a * b; });

std::inner_product (来自 <numeric>)

std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = {4, 5, 6};

// 点积
int dot = std::inner_product(v1.begin(), v1.end(), v2.begin(), 0);

std::iota (来自 <numeric>)

std::vector<int> v(5);

// 填充序列值
std::iota(v.begin(), v.end(), 10); // v = {10, 11, 12, 13, 14}

这些算法可以大大提高C++编程效率,避免了手动编写循环的繁琐工作,同时通常比手写循环更高效。

相关文章:

  • 【C++】前向声明(Forward Declaration)
  • Interaction Toolkit 新版模拟器快捷键
  • [NOIP 2003 普及组] 栈 Java
  • OSM路网简化文档+实操视频讲解(道路中心线提取、拓扑检查,学术论文处理方式)11
  • 基于kitti格式纯点云数据的centerpoint目标检测模型的转换(.pth转.onnx和.plan,更新中)
  • SpringBoot日志
  • 代码训练day25回溯p4
  • 嵌入式程序设计英语
  • java: 需要‘)‘ java: 未结束的字符串文字,java: 不是语句,怎么解决
  • C++ (初始C++,命名空间,引用,函数增强)
  • Java-分布式锁tryLock(0, TimeUnit.SECONDS)中0的含义
  • 大模型中提到的分词器是什么
  • C++算法优化实战:破解性能瓶颈,提升程序效率
  • 【AI】使用 Hugging Face Transformers 进行文本摘要实现
  • (2)VTK C++开发示例 --- 绘制多面锥体
  • 预防WIFI攻击,保证网络安全
  • 《植物大战僵尸融合版v2.4.1》,塔防与创新融合的完美碰撞
  • RHCE第五章:NFS服务器
  • 前端操作document的小方法,主要功能-获取当前页面全部的a标签页,并根据链接中必要的字段进行判断,然后把这些链接放入iframe去打开
  • 【Windows】系统安全移除移动存储设备指南:告别「设备被占用」弹窗
  • 习近平致电祝贺诺沃亚当选连任厄瓜多尔总统
  • 世界读书日|南京图书馆开了首个网络文学主题阅读空间
  • 世遗X时尚,七匹狼这场大秀秀出中国文化独特魅力
  • 文理医工“四轮驱动”,复旦六大新工科创新学院核心团队均亮相
  • 推动行业健康发展,上海发布医药企业防范商业贿赂案例手册
  • 不做“正常”的囚徒