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;
}
相关推荐
浅念-15 小时前
刷穿LeetCode:BFS 解决 Flood Fill 算法
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先
做cv的小昊16 小时前
【TJU】研究生应用统计学课程笔记(8)——第四章 线性模型(4.1 一元线性回归分析)
笔记·线性代数·算法·数学建模·回归·线性回归·概率论
贾斯汀玛尔斯16 小时前
每天学一个算法--倒排索引(Inverted Index)
算法·inverted-index
楼田莉子16 小时前
Linux网络:NAT_代理
linux·运维·服务器·开发语言·c++·后端
小e说说16 小时前
打破偏科困境:这些学习软件助孩子重燃学习热情
算法
南境十里·墨染春水16 小时前
C++日志 2——实现单线程日志系统
java·jvm·c++
zh_xuan16 小时前
api测试工具添加历史记录功能
c++·libcurl·duilib
月昤昽17 小时前
autoCAD二次开发 4.正多边形与collection区分
算法·c#·二次开发·autocad二次开发
休息一下接着来17 小时前
C++ 固定容量环形队列实现
c++·算法
im_AMBER18 小时前
手撕hot100之矩阵!看完这篇就AC~
javascript·数据结构·线性代数·算法·leetcode·矩阵