泛型算法系列29:unique()&&unique_copy()

#include <algorithm> #include <vector> #include <string> #include <iterator> #include <iostream> using namespace std; template <class Type> void print_elements( Type elem ) { cout << elem << " "; } void (*pfi)( int ) = print_elements; void (*pfs)( string ) = print_elements; /************************************************************************/ /* template<class _Iter> struct iterator_traits { // get traits from iterator _Iter typedef typename _Iter::iterator_category iterator_category; typedef typename _Iter::value_type value_type; //save type information here typedef typename _Iter::difference_type difference_type; typedef difference_type distance_type; // retained typedef typename _Iter::pointer pointer; typedef typename _Iter::reference reference; }; */ /************************************************************************/ /************************************************************************/ /* */ template<class _FwdIt> inline _FwdIt my_unique(_FwdIt _First, _FwdIt _Last) { // remove each matching previous _DEBUG_RANGE(_First, _Last); for (_FwdIt _Firstb; (_Firstb = _First) != _Last && ++_First != _Last; ) if (*_Firstb == *_First) { // copy down for (; ++_First != _Last; ) if (!(*_Firstb == *_First)) *++_Firstb = *_First; return (++_Firstb); } return (_Last); } template<class _InIt, class _OutIt> inline _OutIt my_Unique_copy(_InIt _First, _InIt _Last, _OutIt _Dest) { // copy compressing pairs that match, input iterators _DEBUG_POINTER(_Dest); typename iterator_traits<_InIt>::value_type _Val = *_First; for (*_Dest++ = _Val; ++_First != _Last; ) if (!(_Val == *_First))//if (!_Pred(_Val, *_First)) _Val = *_First, *_Dest++ = _Val; return (_Dest); } /************************************************************************/ int main() { int ia[] = { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5 }; vector< int > vec( ia, ia + 10 ); vector< int >::iterator vec_iter; // results in unchanged sequence: 0s are not consecutive // generates: 0 1 0 2 0 3 0 4 0 5 vec_iter = my_unique( vec.begin(), vec.end() ); for_each( vec.begin(), vec.end(), pfi ); cout << "/n/n"; // sort vector: 0 0 0 0 0 1 2 3 4 5 // then apply unique: // generates: 0 1 2 3 4 5 2 3 4 5 sort( vec.begin(), vec.end() ); vec_iter = unique( vec.begin(), vec.end() ); for_each( vec.begin(), vec.end(), pfi ); cout << "/n/n"; // erase the invalid elements from container // generates: 0 1 2 3 4 5 vec.erase( vec_iter, vec.end() ); for_each( vec.begin(), vec.end(), pfi ); cout << "/n/n"; string sa[] = { "enough", "is", "enough", "enough", "is", "good" }; vector< string > svec( sa, sa + 6 ); vector< string > vec_result( svec.size() ); vector< string >::iterator svec_iter; sort( svec.begin(), svec.end() ); svec_iter = my_Unique_copy( svec.begin(), svec.end(), vec_result.begin() ); // generates: enough good is for_each( vec_result.begin(), svec_iter, pfs ); cout << "/n/n"; return 0; }

你可能感兴趣的:(算法,String,vector,iterator,each,reference)