一:用法解析
函数原型:
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function fn);
功能:
对[ first , last )范围内的元素执行Function操作。
例子:
// for_each example
#include <iostream> // std::cout
#include <algorithm> // std::for_each
#include <vector> // std::vector
void myfunction (int i) { // function:
std::cout << ' ' << i;
}
struct myclass { // function object type:
void operator() (int i) {std::cout << ' ' << i;}
} myobject;
int main () {
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(20);
myvector.push_back(30);
std::cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myfunction);
std::cout << '\n';
// or:
std::cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myobject);
std::cout << '\n';
return 0;
}
运行如下:
myvector contains: 10 20 30
myvector contains: 10 20 30
二:源码剖析
// TEMPLATE FUNCTION for_each
template<class _InIt,
class _Fn1> inline
void _For_each(_InIt _First, _InIt _Last, _Fn1& _Func)
{ // perform function for each element
for (; _First != _Last; ++_First)
_Func(*_First);
}
template<class _InIt,
class _Fn1> inline
_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{ // perform function for each element
_DEBUG_RANGE_PTR(_First, _Last, _Func);
_For_each(_Unchecked(_First), _Unchecked(_Last), _Func);
return (_STD move(_Func));
}
源码摘抄自Visual Studio 2015安装目录algorithm文件中。
点击进入目录----> C++源码剖析目录