- for_each: 用指定函数依次对指定范围内所有元素进行迭代访问,可对容器的元素进行修改。
- transform: 与for_each类似,遍历所有元素,可对容器的元素进行修改。
class PrintElem
{
public:
void operator()(int &e)
{
m_n++;
cout << e << " ";
}
void printN()
{
cout << m_n << endl;
}
private:
int m_n;
};
void PrintV(int &n)
{
cout << n << " ";
}
template <typename T>
void PrintElement(vector<T> &v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
}
int Increase(int &i)
{
return i + 99;
}
void Fun1()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
//普通函数 & 回调函数的入口地址
for_each(v1.begin(), v1.end(), PrintV);
//函数对象
for_each(v1.begin(), v1.end(), PrintElem());
//PrintElem p = for_each(v1.begin(), v1.end(), PrintElem());//初始化
PrintElem p;
p = for_each(v1.begin(), v1.end(), PrintElem());//赋值
p.printN();
vector<int> v2;
for (int i = 0; i < 10; i++)
{
v2.push_back(i + 1);
}
cout << endl;
//回调函数
transform(v2.begin(), v2.end(), v2.begin(), Increase);
PrintElement(v2);
cout << endl;
//预定义函数
transform(v2.begin(), v2.end(), v2.begin(), negate<int>());
PrintElement(v2);
cout << endl;
//适配器
list<int> l1;
l1.resize(v2.size());
transform(v2.begin(), v2.end(), l1.begin(), bind2nd(multiplies<int>(), 10));
for (list<int>::iterator it = l1.begin();it != l1.end();it++)
{
cout << *it << " ";
}
cout << endl;
//结合输出迭代器
transform(l1.begin(), l1.end(), ostream_iterator<int>(cout, " "), negate<int>());
cout << endl;
}
它们的不同在于函数对象的返回值上,一般情况下for_each所使用的函数对象,参数是引用,没有返回值。transform所使用的函数对象,参数一般不使用引用,而是还有返回值
for_each源码
template<class _InIt,
class _Fn> inline
_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);//返回函数对象本身
}
transform源码
template<class _InIt,
class _OutIt,
class _Fn> inline
_OutIt transform(const _InIt _First, const _InIt _Last, _OutIt _Dest, _Fn _Func)
{ // transform [_First, _Last) with _Func
_Adl_verify_range(_First, _Last);
auto _UFirst = _Get_unwrapped(_First);
const auto _ULast = _Get_unwrapped(_Last);
auto _UDest = _Get_unwrapped_n(_Dest, _Idl_distance<_InIt>(_UFirst, _ULast));
for (; _UFirst != _ULast; ++_UFirst, (void)++_UDest)
{
*_UDest = _Func(*_UFirst);//有返回值
}
_Seek_wrapped(_Dest, _UDest);
return (_Dest);
}