C++ 泛型算法unique 和unique_copy :删除相邻的重复元素

std::unique

 
C++
 
Algorithm library
 
Defined in header
   
template< class ForwardIt >
ForwardIt unique( ForwardIt first, ForwardIt last );
(1)  
template< class ForwardIt, class BinaryPredicate >
ForwardIt unique( ForwardIt first, ForwardIt last, BinaryPredicate p );
(2)  
     

Removes all consecutive duplicate elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.


eg.

int main(int argc, char* argv[])
{
   list ivec1;

   for(list::size_type i = 0;  i<10 ; ++i)
   {
       ivec1.push_back(i);
   }

   ivec1.push_back(9);

   cout<<"original content:"<::iterator i = ivec1.begin() ; i != ivec1.end() ; ++i)
   {
       cout<<*i< ivec;

   unique_copy(ivec1.begin(),ivec1.end(),back_inserter(ivec));

   cout<<"after unique_copy:"<::iterator i = ivec.begin() ; i != ivec.end() ; ++i)
   {
       cout<<*i<::iterator t = unique(ivec1.begin(),ivec1.end());
    cout<<"after unique:"<::iterator i = ivec1.begin() ; i != t ; ++i)
   {
       cout<<*i<

当list 中元素是0,1,2,3,4,5,6,7,8,9,9时后面的输出都是0,1,2,3,4,5,6,7,8,9;

但是当list 中元素是0,1,2,3,4,5,6,7,8,9,5后面的输出都是0,1,2,3,4,5,6,7,8,9,5


结论

======================================

unique 和其copy版本都只能"删除"相邻的重复元素

你可能感兴趣的:(C++)