描述:
遍历容器元素并执行指定函数。
定义:
template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );
template< class InputIt, class UnaryFunction >
constexpr UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );
可能的实现:
template<class InputIt, class UnaryFunction>
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
for (; first != last; ++first) {
f(*first);
}
return f; // C++11 起隐式移动
}
参数:
first, last - 容器的迭代器范围
f - 函数对象,要应用于解引用范围 [first, last) 中每个迭代器结果的函数
示例:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> vecData = { 1,2,3 };
std::for_each(std::begin(vecData),std::end(vecData),
[](int nData)
{
std::cout << "元素为:" << nData << std::endl;
});
/*
元素为:1
元素为:2
元素为:3
*/
}