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


之前總結了一下我覺得有用的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;
}

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM