1. 程式人生 > >【整理】C++中的unique函數

【整理】C++中的unique函數

函數 數字 元素 vector 整理 rds 總結 改變 new

之前總結了一下我覺得有用的erase,lower_bound,upper_bound。

  • 現在總結一下unique,unique的作用是“去掉”容器中相鄰元素的重復元素(不一定要求數組有序),它會把重復的元素添加到容器末尾(所以數組大小並沒有改變),而返回值是去重之後的尾地址,下面舉個例子。
  • 由於返回的是容器末尾,所以如果想得到去重後的size,需要減去初始地址,lower_bound是得到地址,稍微不同。

如:

  sz = unique(b + 1,b + n + 1)-(b + 1);
  sz = unique(a,a + n) - a;

對比一下lower_bound:

  pos=lower_bound(b + 1,b + sz + 1,a[i]) - b;
  • 或許你會說可以直接模擬。通過再開一個數組,數字與前一個相同的相同的不加入新數組,僅僅多開了一個數組而已,不久搞定了嗎。那麽unique到底有什麽優勢呢?比如,假如要得到相鄰不同的字符串組,用unique就方便些(好像模擬也不麻煩,就當為了“美”而用unique吧)。
sort(words.begin(), words.end()); 
vector<string>::iterator end_unique =  unique(words.begin(), words.end()); 
words.erase(end_unique, words.end());

  • 如果要刪去重復元素,可以把尾巴刪去即可(或者直接定義新的長度!)。
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
int main()
{
    const int N=11;
    int array1[N]={1,2,0,3,3,0,7,7,7,0,8
}; vector<int> vector1; for (int i=0;i<N;++i) vector1.push_back(array1[i]); vector<int>::iterator new_end; new_end=unique(vector1.begin(),vector1.end()); //"刪除"相鄰的重復元素 assert(vector1.size()==N); vector1.erase(new_end,vector1.end()); //刪除(真正的刪除)重復的元素 copy(vector1.begin(),vector1.end(),ostream_iterator<int>(cout," ")); cout<<endl; return 0; }

(代碼當然是舶來品。。。)

【整理】C++中的unique函數