for_each函数原型
<algorithm>
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function fn);
std::for_each
是C++ STL
中的一个算法,它对指定范围内的每个元素执行某个操作。这个函数接受两个迭代器参数,表示要操作的元素范围,以及一个可调用对象(如函数指针、lambda表达式、函数对象、std::function
或std::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产生的可调用对象调用