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;
}
相关推荐
Coding小公仔2 小时前
C++ bitset 模板类
开发语言·c++
凌肖战2 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
菜鸟看点2 小时前
自定义Cereal XML输出容器节点
c++·qt
weixin_478689762 小时前
十大排序算法汇总
java·算法·排序算法
luofeiju3 小时前
使用LU分解求解线性方程组
线性代数·算法
SKYDROID云卓小助手3 小时前
无人设备遥控器之自动调整编码技术篇
人工智能·嵌入式硬件·算法·自动化·信号处理
悲伤小伞3 小时前
linux_git的使用
linux·c语言·c++·git
ysa0510303 小时前
数论基础知识和模板
数据结构·c++·笔记·算法
GEEK零零七4 小时前
Leetcode 1103. 分糖果 II
数学·算法·leetcode·等差数列
今天背单词了吗9804 小时前
算法学习笔记:7.Dijkstra 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·数据结构·笔记·算法