unique_copy:在unique的基础上,不改变源容器,并将得到的结果复制给_Dest.
template<class _FwdIt,
class_OutIt,
class_Pr> inline
_OutIt _Unique_copy(_FwdIt _First,_FwdIt _Last,
_OutIt _Dest, _Pr _Pred,forward_iterator_tag)
{ // copy compressing pairs satisfying _Pred, forwarditerators
_FwdIt _Firstb = _First;
for(*_Dest++ = *_Firstb; ++_First != _Last; )
if(!_Pred(*_Firstb, *_First))
{ // copyunmatched
_Firstb = _First;
*_Dest++ = *_Firstb;
}
return(_Dest);
}
对应的一个函数:
template<class _FwdIt,
class_OutIt,
class_Pr> inline
_OutIt _Unique_copy(_FwdIt _First,_FwdIt _Last,
_OutIt _Dest, _Pr _Pred,forward_iterator_tag)
{ // copy compressing pairs satisfying _Pred, forwarditerators
_FwdIt _Firstb = _First;
for(*_Dest++ = *_Firstb; ++_First != _Last; )
if(!_Pred(*_Firstb, *_First))//循环体之所以比unique简单,原因在于,有额外的容器提供保存值.
{ // copyunmatched
_Firstb = _First;
*_Dest++ = *_Firstb;
}
return(_Dest);
}
举例:
1. int main()
2. {
3. typedef vector<int>vecIntContains;
4. vecIntContainsvecInt;
5. vecInt.push_back(2 );
6. vecInt.push_back(7 );
7. vecInt.push_back(7 );
8. vecInt.push_back(5 );
9. vecInt.push_back(4 );
10. vecInt.push_back(1 );
11. vecInt.push_back(4 );
12. vecInt.push_back(1 );
13. vecIntContainsvecNew;
14. unique_copy(vecInt.begin(),vecInt.end(),ostream_iterator<int>(cout," " ) );//left > right
15.
16. cout<<"\nunique second operator:\n";
17. unique_copy(vecInt.begin(),vecInt.end() - 1,ostream_iterator<int>(cout," " ),greater<int>() );//left >right
18. system( "pause" );
19. return 0;
20. }
21.
这里需要注意的一个小问题是,14行返回值不是vector<int>::iterator.