95.STL-遍历算法 for_each

算法概述:

算法主要是由头文件 <algorithm> <functional> <numeric> 组成。

<algorithm> 是所有STL头文件中最大的一个,范围涉及到比较、 交换、查找、遍历操作、复制、修改等等

<numeric> 体积很小,只包括几个在序列上面进行简单数学运算的模板函数

<functional> 定义了一些模板类,用以声明函数对象。

for_each

是 C++ 标准模板库(STL)中的一个算法,用于对一个范围内的每个元素应用一个函数。以下是简要解释和一个示例:

std::for_each 语法:

复制代码
template <class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function fn);
  • 参数:

    • firstlast: 表示范围的输入迭代器。
    • fn: 接受范围内元素的一元函数。
  • 返回值:

    • fn(函数对象)。

代码示例1:

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

void printSquare(int x) {
    std::cout << x * x << " ";
}

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

    // 使用 std::for_each 打印每个元素的平方
    std::for_each(numbers.begin(), numbers.end(), printSquare);

    return 0;
}

代码示例2:

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

using namespace std;
//普通函数
void print01(int val)
{
	cout << val << " ";
}
//函数对象
class print02
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
//for_each算法基本用法
void test01() {
	vector<int> v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	//遍历算法
	for_each(v.begin(), v.end(), print01);
	cout << endl;
	for_each(v.begin(), v.end(), print02());
	cout << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
相关推荐
楼田莉子22 分钟前
C++学习:异常及其处理
开发语言·c++·学习·visual studio
微笑尅乐40 分钟前
从递归到迭代吃透树的层次——力扣104.二叉树的最大深度
算法·leetcode·职场和发展
im_AMBER43 分钟前
Leetcode 28
算法·leetcode
杰 .1 小时前
C++ Hash
数据结构·c++·哈希算法
GHL2842710901 小时前
用PDH库获取CPU使用率(源码)
c++
让我们一起加油好吗1 小时前
【基础算法】多源 BFS
c++·算法·bfs·宽度优先·多源bfs
冷崖1 小时前
定时器的学习(二)
linux·c++·学习
B站计算机毕业设计之家1 小时前
深度学习实战:python动物识别分类检测系统 计算机视觉 Django框架 CNN算法 深度学习 卷积神经网络 TensorFlow 毕业设计(建议收藏)✅
python·深度学习·算法·计算机视觉·分类·毕业设计·动物识别
大胆飞猪1 小时前
高并发内存池日志
c++·项目
And_Ii1 小时前
LeetCode 3350. 检测相邻递增子数组 II
数据结构·算法·leetcode