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;
}
相关推荐
初願致夕霞14 分钟前
Linux_进程
linux·c++
Thera7771 小时前
【Linux C++】彻底解决僵尸进程:waitpid(WNOHANG) 与 SA_NOCLDWAIT
linux·服务器·c++
Wei&Yan1 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
wregjru1 小时前
【QT】4.QWidget控件(2)
c++
浅念-1 小时前
C++入门(2)
开发语言·c++·经验分享·笔记·学习
小羊不会打字1 小时前
CANN 生态中的跨框架兼容桥梁:`onnx-adapter` 项目实现无缝模型迁移
c++·深度学习
团子的二进制世界1 小时前
G1垃圾收集器是如何工作的?
java·jvm·算法
Max_uuc1 小时前
【C++ 硬核】打破嵌入式 STL 禁忌:利用 std::pmr 在“栈”上运行 std::vector
开发语言·jvm·c++
吃杠碰小鸡1 小时前
高中数学-数列-导数证明
前端·数学·算法
故事不长丨1 小时前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#