【C++基础】std::for_each

本文详细介绍了C++STL中的for_each函数,探讨了如何使用普通函数、函数指针、函数对象、Lambda表达式、std::function和std::bind等可调用对象来执行遍历操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


for_each函数原型

<algorithm>

template <class InputIterator, class Function>
   Function for_each (InputIterator first, InputIterator last, Function fn);

std::for_eachC++ STL中的一个算法,它对指定范围内的每个元素执行某个操作。这个函数接受两个迭代器参数,表示要操作的元素范围,以及一个可调用对象(如函数指针、lambda表达式、函数对象、std::functionstd::bind)作为第三个参数,该调用对象定义了应用于范围内每个元素的操作。

可调用对象

在C++中,可调用对象(Callable Object)是指那些可以像函数一样被调用的实体。这包括但不限于以下几种类型:

普通函数

void print(int num_) {
    std::cout << num_ << std::endl;
}
std::vector<int> vec = {1, 2, 3};
std::for_each(vec.begin(),vec.end(),print);

函数指针

void (*funcPtr)(int) = &print;
std::for_each(vec.begin(),vec.end(),funcPtr); // 函数指针作为可调用对象调用

函数对象

class MyClass
{
	void operator()(int num_ )
	{
		std::cout << num_ << std::endl;
	}
};

MyClass my_class;
std::for_each(vec.begin(),vec.end(),my_class); // 函数对象作为可调用对象调用

Lambda表达式

std::for_each(vec.begin(), vec.end(), [](int num_ ){ std::cout << num_ << std::endl; }); // Lambda作为可调用对象传递给std::for_each

std::function(C++11以后)

std::function<void(int)> callableAction = print;
std::for_each(vec.begin(),vec.end(),callableAction ); // std::function包装的任意可调用对象调用

std::bind(C++11以后)

using namespace std::placeholders; // 为了使用 `_1`, `_2`, ...
auto boundFunction = std::bind(print, _1);

std::for_each(vec.begin(),vec.end(),boundFunction); // std::bind产生的可调用对象调用
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值