C++ Algorithm 常用算法

C++ <algorithm> 头文件是标准库中提供的一系列算法,用于操作范围(range)内的元素。这些算法可以用于数组、容器如vector和list,以及其他满足相应迭代器要求的数据结构。以下是一些常用的C++ <algorithm> 中的算法及其使用示例。

1. std::sort:排序

对给定范围内的元素进行排序。默认情况下,按照升序排列,但也可以指定自定义比较函数。

cpp 复制代码
#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {5, 3, 1, 4, 2};
    std::sort(v.begin(), v.end());
    for (int i : v) std::cout << i << ' '; // 输出:1 2 3 4 5
    return 0;
}

2. std::count_if:计数满足条件的元素

计算范围内满足特定条件的元素数量。

cpp 复制代码
#include <algorithm>
#include <vector>
#include <iostream>

bool is_even(int n) { return n % 2 == 0; }

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6};
    int count = std::count_if(v.begin(), v.end(), is_even);
    std::cout << "Even numbers: " << count << std::endl; // 输出:Even numbers: 3
    return 0;
}

3. std::find_if:查找第一个满足条件的元素

返回指向范围内第一个满足特定条件的元素的迭代器。

cpp 复制代码
#include <algorithm>
#include <vector>
#include <iostream>

bool is_target(int n) { return n == 42; }

int main() {
    std::vector<int> v = {10, 20, 30, 42, 50};
    auto it = std::find_if(v.begin(), v.end(), is_target);
    if (it != v.end()) std::cout << "Found: " << *it << std::endl; // 输出:Found: 42
    else std::cout << "Not found" << std::endl;
    return 0;
}

4. std::transform:转换范围

对范围内的每个元素应用一个函数,并将结果存储在另一个容器或序列中。

cpp 复制代码
#include <algorithm>
#include <vector>
#include <iostream>

int square(int n) { return n * n; }

int main() {
    std::vector<int> v1 = {1, 2, 3, 4, 5};
    std::vector<int> v2(v1.size());
    std::transform(v1.begin(), v1.end(), v2.begin(), square);
    for (int i : v2) std::cout << i << ' '; // 输出:1 4 9 16 25
    return 0;
}

5. std::accumulate:累积值

对范围内的元素执行累积操作,如求和、求乘积等。

cpp 复制代码
#include <algorithm>
#include <vector>
#include <iostream>
#include <numeric>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    int sum = std::accumulate(v.begin(), v.end(), 0);
    std::cout << "Sum: " << sum << std::endl; // 输出:Sum: 15
    return 0;
}

6. std::remove_if:移除满足条件的元素

将不满足特定条件的元素移动到范围的前端,并返回新的逻辑结束位置的迭代器。实际删除操作需配合容器的erase方法。

cpp 复制代码
#include <algorithm>
#include <vector>
#include <iostream>

bool is_odd(int n) { return n % 2 != 0; }

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6};
    auto new_end = std::remove_if(v.begin(), v.end(), is_odd);
    v.erase(new_end, v.end()); // 实际删除操作
    for (int i : v) std::cout << i << ' '; // 输出:2 4 6
    return 0;
}
相关推荐
海蓝可知天湛6 分钟前
利用Genspark自定义智能体:算法竞赛测试数据反推与生成工具
算法·aigc
BothSavage10 分钟前
Qwen3-VL-8B-Instruct推理测试transformer+sglang双版本
算法
尤超宇27 分钟前
YOLOv3 目标检测算法核心技术
算法·yolo·目标检测
云泽80844 分钟前
C/C++内存管理详解:从基础原理到自定义内存池原理
java·c语言·c++
cyclel1 小时前
散列表的小想法
算法
Code小翊1 小时前
堆的基础操作,C语言示例
java·数据结构·算法
余俊晖1 小时前
如何让多模态大模型学会“自动思考”-R-4B训练框架核心设计与训练方法
人工智能·算法·机器学习
Emilia486.1 小时前
【Leetcode&nowcode&数据结构】顺序表的应用
数据结构·算法·leetcode
一水鉴天1 小时前
整体设计 逻辑系统程序 之27 拼语言整体设计 9 套程序架构优化与核心组件(CNN 改造框架 / Slave/Supervisor/ 数学工具)协同设计
人工智能·算法
小年糕是糕手1 小时前
【数据结构】双向链表“0”基础知识讲解 + 实战演练
c语言·开发语言·数据结构·c++·学习·算法·链表