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;
}
相关推荐
Trent198534 分钟前
影楼精修-肤色统一算法解析
图像处理·人工智能·算法·计算机视觉
feifeigo12337 分钟前
高光谱遥感图像处理之数据分类的fcm算法
图像处理·算法·分类
a东方青1 小时前
蓝桥杯 2024 C++国 B最小字符串
c++·职场和发展·蓝桥杯
北上ing2 小时前
算法练习:19.JZ29 顺时针打印矩阵
算法·leetcode·矩阵
.格子衫.3 小时前
真题卷001——算法备赛
算法
XiaoyaoCarter3 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
galaxy_strive3 小时前
qtc++ qdebug日志生成
开发语言·c++·qt
Hygge-star3 小时前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
Darkwanderor3 小时前
c++STL-list的模拟实现
c++·list
Humbunklung4 小时前
Visual Studio 2022 中添加“高级保存选项”及解决编码问题
前端·c++·webview·visual studio