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;
}
相关推荐
罗湖老棍子5 分钟前
最小函数值(minval)(信息学奥赛一本通- P1370)
数据结构·c++·算法··优先队列·
LYFlied6 分钟前
【每日算法】LeetCode 4. 寻找两个正序数组的中位数
算法·leetcode·面试·职场和发展
长安er7 分钟前
LeetCode 62/64/5/1143多维动态规划核心题型总结
算法·leetcode·mybatis·动态规划
LYFlied12 分钟前
【每日算法】LeetCode 208. 实现 Trie (前缀树)
数据结构·算法·leetcode·面试·职场和发展
肆悟先生13 分钟前
3.17 内联函数
c++
代码游侠40 分钟前
应用——MPlayer 媒体播放器系统代码详解
linux·运维·笔记·学习·算法
学编程就要猛1 小时前
算法:3.快乐数
java·算法
AI科技星1 小时前
统一场论框架下万有引力常数的量子几何涌现与光速关联
数据结构·人工智能·算法·机器学习·重构
仰泳的熊猫1 小时前
1109 Group Photo
数据结构·c++·算法·pat考试
SunkingYang1 小时前
MFC中事件与消息有什么关联,区别与联系
c++·mfc·消息·事件·区别·联系·关联