Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
C++如何使用for_each算法_C++标准算法遍历容器的用法_创想鸟

C++如何使用for_each算法_C++标准算法遍历容器的用法

for_each是中的算法,用于遍历容器元素并执行操作,支持lambda、函数指针和仿函数,可修改元素值但不改变容器结构。

c++如何使用for_each算法_c++标准算法遍历容器的用法

for_each 是 C++ 标准库中定义在 gorithm> 头文件里的一个通用算法,用于对容器中的每个元素执行指定的操作。它比传统的 for 循环更简洁、安全,并支持函数指针、函数对象(仿函数)以及 lambda 表达式等多种调用方式。

包含必要的头文件

使用 for_each 前,必须包含 和对应的容器头文件,例如 :

#include
#include
#include iostream>

基本语法

for_each 的函数原型如下:

template
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f);

它接受三个参数:

立即学习“C++免费学习笔记(深入)”;

first:起始迭代器 last:结束迭代器(不包含) f:可调用对象,对每个元素执行操作

返回值是传入的函数对象(可用于有状态的仿函数)。

使用方式示例

以下通过 vector 容器演示几种常见的 for_each 用法。

1. 使用 Lambda 表达式(推荐)

Lambda 让代码更直观,适合简单操作:

std::vector nums = {1, 2, 3, 4, 5};

std::for_each(nums.begin(), nums.end(), [](int n) {
    std::cout });
// 输出: 1 2 3 4 5

2. 使用函数指针

定义一个普通函数,然后传入:

void print(int n) {
    std::cout }

std::for_each(nums.begin(), nums.end(), print);

3. 使用函数对象(仿函数)

适用于需要保存状态的场景:

struct Accumulate {
    int sum = 0;
    void operator()(int n) { sum += n; }
};

Accumulate acc = std::for_each(nums.begin(), nums.end(), Accumulate());
std::cout

4. 修改容器元素

若需修改元素,应使用引用参数:

std::for_each(nums.begin(), nums.end(), [](int& n) {
    n *= 2;
});
// nums 变为 {2, 4, 6, 8, 10}

适用所有标准容器

for_each 不仅适用于 vector,还可用于 list、deque、set、map 等任何提供迭代器的容器。例如遍历 map:

std::map ages = {{“Alice”, 25}, {“Bob”, 30}};

std::for_each(ages.begin(), ages.end(), [](const auto& pair) {
    std::cout });

基本上就这些。for_each 提供了一种更现代、更安全的遍历方式,结合 lambda 使用非常高效。注意它不会改变容器结构,但可通过引用修改元素值。

以上就是C++如何使用for_each算法_C++标准算法遍历容器的用法的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1485167.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
C++怎么实现一个桥接设计模式_C++结构型模式与实现和抽象分离
上一篇 2025年12月19日 08:41:48
C++怎么实现一个希尔排序_C++排序算法与希尔排序实现
下一篇 2025年12月19日 08:41:59

相关推荐

发表回复

登录后才能评论
关注微信