STL Algorithms 之 unique

來源:互聯網
上載者:User

C++的文檔中說,STL中的unique是類似於這樣實現的:

template <class ForwardIterator>  ForwardIterator unique ( ForwardIterator first, ForwardIterator last ){  ForwardIterator result=first;  while (++first != last)  {    if (!(*result == *first))  // or: if (!pred(*result,*first)) for the pred version      *(++result)=*first;  }  return ++result;}

仔細一看就知道,它並不是幫你直接把一個數組中所有重複的元素除去,而是對數組掃描一次,只看當前元素和前面一個元素,如果當前值和前面的值相等,那麼跳過,否則就把這個值算上,迭代器遞增,最後返回給你一個位置,表示我掃描到多少個當前值與其前面一個元素值不同的元素。

所以,要真正利用好unique,我們必須先對我們所需要進行unique操作的數組排序,然後再使用unique。

這樣以後其實還是不滿足我們的要求的,因為實際上unique函數實現的只是把不同的元素“unique”放到數組的前面,而數組的後面還有一段重複的沒有去掉。這個時候就可以利用到unique函數的傳回值啦,它返回的就是重複元素出現的第一個位置。

另外,unique函數可以接受兩個參數(數組的開頭,數組的末尾),也可以接受三個參數(數組的開頭,數組的末尾,兩個元素的比較(即定義怎樣算元素相等))

看一下執行個體吧:

// resizing vector#include <iostream>#include <vector>#include <algorithm>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;    it = unique (myvector.begin(), myvector.end()); // 10 20 30 20 10 ?  ?  ?  ?  //尖所指即it的位置                                //                ^                                                                myvector.erase( it , myvector.end() );       // 第一種去掉末尾的方法  cout << "first: myvector contains:";  for (int i=0;i<myvector.size();i++)    cout << " " << myvector[i];  cout<<endl;  sort(myvector.begin(),myvector.end());        //先排序  it = unique (myvector.begin(), myvector.end(), myfunction);     // 使用比較函數,但此處是跟預設的比較一樣的。  myvector.resize( it - myvector.begin() );       // 10 20 30   cout << "second: myvector contains:";  for (it=myvector.begin(); it!=myvector.end(); ++it)    cout << " " << *it;  cout << endl;  return 0;}/*輸出:first: myvector contains: 10 20 30 20 10second: myvector contains: 10 20 30*/

 

 

 

轉載  : http://wonderflow.info/archives/424

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.