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

相关推荐
C++、Java和Python的菜鸟1 小时前
第六章 统计初步
算法·机器学习·概率论
Cx330❀1 小时前
【数据结构初阶】--排序(五):计数排序,排序算法复杂度对比和稳定性分析
c语言·数据结构·经验分享·笔记·算法·排序算法
杜子不疼.1 小时前
《Python学习之字典(一):基础操作与核心用法》
开发语言·python·学习
散1121 小时前
01数据结构-Prim算法
数据结构·算法·图论
起个昵称吧1 小时前
线程相关编程、线程间通信、互斥锁
linux·算法
落霞的思绪2 小时前
Java设计模式详细解读
java·开发语言·设计模式
阿巴~阿巴~2 小时前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
myzzb2 小时前
基于uiautomation的自动化流程RPA开源开发演示
运维·python·学习·算法·自动化·rpa
java1234_小锋2 小时前
一周学会Matplotlib3 Python 数据可视化-绘制自相关图
开发语言·python·信息可视化·matplotlib·matplotlib3
甄超锋2 小时前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven