STL 去重 unique
生活随笔
收集整理的這篇文章主要介紹了
STL 去重 unique
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一.unique函數
類屬性算法unique的作用是從輸入序列中“刪除”所有相鄰的重復元素。
該算法刪除相鄰的重復元素,然后重新排列輸入范圍內的元素,并且返回一個迭代器(容器的長度沒變,只是元素順序改變了),表示無重復的值范圍得結束。
1 // sort words alphabetically so we can find the duplicates 2 sort(words.begin(), words.end()); 3 /* eliminate duplicate words: 4 * unique reorders words so that each word appears once in the 5 * front portion of words and returns an iterator one past the 6 unique range; 7 * erase uses a vector operation to remove the nonunique elements 8 */ 9 vector<string>::iterator end_unique = unique(words.begin(), words.end()); 10 words.erase(end_unique, words.end());在STL中unique函數是一個去重函數, unique的功能是去除相鄰的重復元素(只保留一個),其實它并不真正把重復的元素刪除,是把重復的元素移到后面去了,然后依然保存到了原數組中,然后 返回去重后最后一個元素的地址,因為unique去除的是相鄰的重復元素,所以一般用之前都會要排一下序。
若調用sort后,vector的對象的元素按次序排列如下:
sort jumps over quick red red slow the the turtle則調用unique后,vector中存儲的內容是:
注意,words的大小并沒有改變,依然保存著10個元素;只是這些元素的順序改變了。調用unique“刪除”了相鄰的重復值。給“刪除”加上引號是因為unique實際上并沒有刪除任何元素,而是將無重復的元素復制到序列的前段,從而覆蓋相鄰的重復元素。unique返回的迭代器指向超出無重復的元素范圍末端的下一個位置。
注意:算法不直接修改容器的大小。如果需要添加或刪除元素,則必須使用容器操作。
1 #include <iostream>2 #include <cassert>3 #include <algorithm>4 #include <vector>5 #include <string>6 #include <iterator>7 using namespace std;8 9 int main() 10 { 11 //cout<<"Illustrating the generic unique algorithm."<<endl; 12 const int N=11; 13 int array1[N]={1,2,0,3,3,0,7,7,7,0,8}; 14 vector<int> vector1; 15 for (int i=0;i<N;++i) 16 vector1.push_back(array1[i]); 17 18 vector<int>::iterator new_end; 19 new_end=unique(vector1.begin(),vector1.end()); //"刪除"相鄰的重復元素 20 assert(vector1.size()==N); 21 22 vector1.erase(new_end,vector1.end()); //刪除(真正的刪除)重復的元素 23 copy(vector1.begin(),vector1.end(),ostream_iterator<int>(cout," ")); 24 cout<<endl; 25 26 return 0; 27 }?
?
轉載于:https://www.cnblogs.com/fish7/p/4391035.html
總結
以上是生活随笔為你收集整理的STL 去重 unique的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]使用CSS3 Grid布局实现内容
- 下一篇: 历届试题 错误票据