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: 

#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:  

#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;
}

  • 13
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清酒。233

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值