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;
}
相关推荐
知识浅谈3 小时前
DeepSeek V4 和 GPT-5.5 在同一天发布了??我也很懵,但对比完我悟了
算法
DeepModel3 小时前
通俗易懂讲透 Q-Learning:从零学会强化学习核心算法
人工智能·学习·算法·机器学习
田梓燊3 小时前
力扣:19.删除链表的倒数第 N 个结点
算法·leetcode·链表
handler015 小时前
从零实现自动化构建:Linux Makefile 完全指南
linux·c++·笔记·学习·自动化
简简单单做算法5 小时前
基于GA遗传优化双BP神经网络的时间序列预测算法matlab仿真
神经网络·算法·matlab·时间序列预测·双bp神经网络
guygg885 小时前
利用遗传算法解决列车优化运行问题的MATLAB实现
开发语言·算法·matlab
武藤一雄6 小时前
19个核心算法(C#版)
数据结构·windows·算法·c#·排序算法·.net·.netcore
sali-tec6 小时前
C# 基于OpenCv的视觉工作流-章52-交点查找
图像处理·人工智能·opencv·算法·计算机视觉
我头发多我先学6 小时前
C++ 模板全解:从泛型编程初阶到特化、分离编译进阶
java·开发语言·c++
yu85939586 小时前
MATLAB连续线性化模型预测控制(SL-MPC)
算法·机器学习·matlab