C++ 的标准模板库(STL)常用算法介绍

C++ 的标准模板库(STL)提供了丰富的算法,用于对容器中的元素进行各种操作和处理。下面我将介绍几个常用的 STL 算法,并为每个算法提供一个简单的示例来说明其基本用法。

1. std::for_each(遍历)

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

void print(int i) {
    std::cout << i << " ";
}

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

    // 使用 for_each 算法遍历输出容器中的元素
    std::for_each(vec.begin(), vec.end(), print);

    return 0;
}

2. std::transform(转换)

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

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

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::vector<int> result;

    // 使用 transform 算法对容器中的元素进行转换
    std::transform(vec.begin(), vec.end(), std::back_inserter(result), square);

    // 输出转换后的元素
    for (int i : result) {
        std::cout << i << " ";
    }

    return 0;
}

3. std::sort(排序)

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

int main() {
    std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5};

    // 使用 sort 算法对容器中的元素进行排序
    std::sort(vec.begin(), vec.end());

    // 输出排序后的元素
    for (int i : vec) {
        std::cout << i << " ";
    }

    return 0;
}

4. std::accumulate(累加)

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

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

    // 使用 accumulate 算法对容器中的元素进行累加
    int sum = std::accumulate(vec.begin(), vec.end(), 0);

    std::cout << "Sum: " << sum << std::endl;

    return 0;
}

通过这些简单的示例,你可以了解到如何使用 C++ STL 中的一些常用算法(for_each、transform、sort、accumulate),并对容器中的元素进行遍历、转换、排序和累加等操作。希望这些示例能帮助你更好地理解 STL 算法的使用。

相关推荐
王老师青少年编程14 分钟前
csp信奥赛C++高频考点专项训练之字符串 --【字符串基础】:输出亲朋字符串
c++·字符串·csp·高频考点·信奥赛·专项训练·输出亲朋字符串
MediaTea33 分钟前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z43 分钟前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
WBluuue1 小时前
数据结构与算法:莫队(一):普通莫队与带修莫队
c++·算法
小郑加油1 小时前
python学习Day12:pandas安装与实际运用
开发语言·python·学习
AC赳赳老秦1 小时前
投标合规提效:用 OpenClaw 实现标书 / 合同自动审核、关键词校验、格式优化,降低废标风险
开发语言·前端·python·eclipse·emacs·deepseek·openclaw
风筝在晴天搁浅1 小时前
n个六面的骰子,扔一次之后和为k的概率是多少?
算法
KuaCpp1 小时前
C++面向对象(速过复习版)
开发语言·c++
wbs_scy2 小时前
Linux线程同步与互斥(三):线程同步深度解析之POSIX 信号量与环形队列生产者消费者模型,从原理到源码彻底吃透
java·开发语言
2zcode2 小时前
基于MATLAB元胞自动机(CA)的AZ80A镁合金动态再结晶(DRX)过程模拟
开发语言·matlab·动态再结晶