c++的unique函式
阿新 • • 發佈:2021-02-18
技術標籤:c++
在STL中unique函式是一個去重函式, unique的功能是去除相鄰的重複元素(只保留一個),其實它並不真正把重複的元素刪除,是把重複的元素移到後面去了,然後依然儲存到了原陣列中,然後 返回去重後最後一個元素的地址,因為unique去除的是相鄰的重複元素,所以一般用之前都會要排一下序。
注意,words的大小並沒有改變,依然儲存著10個元素;只是這些元素的順序改變了。呼叫unique“刪除”了相鄰的重複值。給“刪除”加上引號是因為unique實際上並沒有刪除任何元素,而是將無重複的元素複製到序列的前段,從而覆蓋相鄰的重複元素。unique返回的迭代器指向超出無重複的元素範圍末端的下一個位置。``
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
int main()
{
//cout<<"Illustrating the generic unique algorithm."<<endl;
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);
//assert巨集的原型定義在<assert.h>中,其作用是如果它的條件返回錯誤,則終止程式執行,原型定義:
//#include <assert.h>
//void assert( int expression );
//assert的作用是現計算表示式 expression ,如果其值為假(即為0),
//那麼它先向stderr列印一條出錯資訊
vector1.erase(new_end,vector1.end()); //刪除(真正的刪除)重複的元素
copy(vector1.begin(),vector1.end(),ostream_iterator<int>(cout," "));
//標頭檔案
//#include<algorithm>
//將a[0]~a[2]複製到b[5]~b[7] 並且覆蓋掉原來的資料 (主要用於容器之間)
copy(a.begin(),a.begin()+3,b.begin()+4);
cout<<endl;
return 0;
}