以求无重复集合为例:

代码
#include<iostream>
#include
<algorithm>//for_each函数
#include<list>

using namespace std; 
void Print(double n){cout<<n;}
int main(){
    
int arr[20]={5,4,6,3,4,2,3,5,6,7,3,4,6,7,5,4,3,2,5,4};
    list
<int> arrI;
    
for(int i=0;i<20;i++)
        arrI.push_back(arr[i]);
    arrI.sort();
    arrI.unique();
    for_each(arrI.begin(),arrI.end(),Print);
    
return 0;
}

 

注:unique函数功能是去除相邻的重复元素,注意是相邻,所以必须先使用sort函数。

对于大多数的STL,unique并不能真正的删除重复元素,而是把重复的一些放在最后,如vector见下例:

 

代码
#include <iostream>
#include 
<algorithm>
#include 
<vector>
using namespace std;

bool myfunction (int i, int j) {
  
return (i==j);
}

int main () {
  
int myints[] = {10,20,20,20,30,30,20,20,10};    // 10 20 20 20 30 30 20 20 10
  vector<int> myvector (myints,myints+9);
  vector
<int>::iterator it;

  
// using default comparison:
  it = unique (myvector.begin(), myvector.end()); // 10 20 30 20 10 30 20 20 10
                                                  
//                ^

  myvector.resize( it 
- myvector.begin() );       // 10 20 30 20 10

  
// using predicate comparison:
  unique (myvector.begin(), myvector.end(), myfunction);   // (no changes)

  
// print out content:
  cout << "myvector contains:";
  
for (it=myvector.begin(); it!=myvector.end(); ++it)
    cout 
<< " " << *it;

  cout 
<< endl;

  
return 0;
}

 

 

这个例子把unique的功能,返回值表现的非常清楚;

如果熟悉,还可以再简短一些:

 

a.erase(unique(a.begin(), a.end()), a.end())

 

 

posted on 2010-11-06 17:34  子桥  阅读(4933)  评论(0编辑  收藏  举报