源码:
// FUNCTION TEMPLATE for_each
template <class _InIt, class _Fn>
_CONSTEXPR20 _Fn for_each(_InIt _First, _InIt _Last, _Fn _Func) { // perform function for each element [_First, _Last)
_Adl_verify_range(_First, _Last);
auto _UFirst = _Get_unwrapped(_First);
const auto _ULast = _Get_unwrapped(_Last);
for (; _UFirst != _ULast; ++_UFirst) {
_Func(*_UFirst);//即把每个元素都解引用解出来,在放进你传入的那个函数中
}
return _Func;
}
使用:
void Print1(int val)
{
cout << val << endl;
}
class Print2
{
public:
void operator()(int val)
{
cout << val << endl;
}
};
void test01()
{
vector<bool>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), Print1);//普通函数作为第三个参数,把函数名放进去
for_each(v.begin(), v.end(), Print2());//仿函数做第三个参数,可以把匿名对象放进去
}
for_each在实际开发中很常用
class Trans
{
public:
int operator()(int val)
{
return val + 100;
}
};
class myPrint
{
public:
void operator()(int val)
{
cout << val << " ";
}
};
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), myPrint());//0 1 2...
cout << endl;
vector<int>vTarget;//目标容器
vTarget.resize(v.size());//目标容器必须提前开阔空间
transform(v.begin(), v.end(), vTarget.begin(), Trans());//将原容器v中的元素加100后放入新的vTarget中
for_each(vTarget.begin(), vTarget.end(), myPrint());//100,101,102。。。
cout << endl;
}