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 算法的使用。

相关推荐
Ulyanov15 分钟前
用Pyglet打造AI数字猎人:从零开始的Python游戏开发与强化学习实践
开发语言·人工智能·python
独自归家的兔31 分钟前
OCPP 1.6 协议详解:StatusNotification 状态通知指令
开发语言·数据库·spring boot·物联网
希望永不加班36 分钟前
Spring AOP 代理模式:CGLIB 与 JDK 动态代理区别
java·开发语言·后端·spring·代理模式
RNEA ESIO1 小时前
PHP进阶-在Ubuntu上搭建LAMP环境教程
开发语言·ubuntu·php
23471021271 小时前
4.15 学习笔记
开发语言·软件测试·python
零号全栈寒江独钓1 小时前
基于c/c++实现linux/windows跨平台获取ntp网络时间戳
linux·c语言·c++·windows
CSCN新手听安1 小时前
【linux】高级IO,以ET模式运行的epoll版本的TCP服务器实现reactor反应堆
linux·运维·服务器·c++·高级io·epoll·reactor反应堆
被开发耽误的大厨1 小时前
1、==、equals、hashCode底层原理?重写场景?
算法·哈希算法
java1234_小锋2 小时前
Java高频面试题:什么是可重入锁?
java·开发语言
WolfGang0073212 小时前
代码随想录算法训练营 Day38 | 动态规划 part11
算法·动态规划