replace_copy:这个函数和replace对应,唯一不同的是,它将得到的结果存在另一个容器里面
// TEMPLATEFUNCTION replace_copy
template<class _InIt,
class_OutIt,
class_Ty> inline
_OutIt _Replace_copy(_InIt _First,_InIt _Last,
_OutIt _Dest, const _Ty& _Oldval, const_Ty& _Newval)
{ // copy replacing each matching _Oldval with _Newval
for (;_First != _Last; ++_First, ++_Dest)
*_Dest = *_First == _Oldval ?_Newval : *_First;
return(_Dest);
}
replace_copy_if:这个函数和replace_if对应,唯一不同的是,它将得到的结果存在另一个容器里面
//TEMPLATE FUNCTION replace_copy_if
template<class _InIt,
class_OutIt,
class_Pr,
class_Ty> inline
_OutIt _Replace_copy_if(_InIt _First,_InIt _Last,
_OutIt _Dest, _Pr _Pred, const _Ty& _Val)
{ // copy replacing each satisfying _Pred with _Val
for (;_First != _Last; ++_First, ++_Dest)
*_Dest = _Pred(*_First) ?_Val : *_First;
return(_Dest);
}
函数同样也很简单.
举例:
bool isTrue( T _val )
{
return( _val % 2 ) == 0;
}
int main()
{
vector<int>vecInt;
for ( int i = 0;i < 10;++ i)
{
vecInt.push_back( i );
}
vector<int>vecDest;
cout<<"vecIntsource:\n";
copy(vecInt.begin(),vecInt.end(),ostream_iterator<int>(cout," " ) );
replace_copy(vecInt.begin(),vecInt.end(),back_inserter( vecDest ),1,2 );
cout<<"\nvecIntreplace:\n";
copy(vecDest.begin(),vecDest.end(),ostream_iterator<int>(cout," " ) );
replace_copy_if(vecInt.begin(),vecInt.end(),vecDest.begin(),isTrue<int>,10);
cout<<"\nvecIntreplace:\n";
copy(vecDest.begin(),vecDest.end(),ostream_iterator<int>(cout," " ) );
system( "pause");
return0;
}