STL 去重 unique
一.unique函數(shù)
類屬性算法unique的作用是從輸入序列中“刪除”所有相鄰的重復(fù)元素。
該算法刪除相鄰的重復(fù)元素,然后重新排列輸入范圍內(nèi)的元素,并且返回一個(gè)迭代器(容器的長(zhǎng)度沒(méi)變,只是元素順序改變了),表示無(wú)重復(fù)的值范圍得結(jié)束。
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函數(shù)是一個(gè)去重函數(shù), unique的功能是去除相鄰的重復(fù)元素(只保留一個(gè)),其實(shí)它并不真正把重復(fù)的元素刪除,是把重復(fù)的元素移到后面去了,然后依然保存到了原數(shù)組中,然后 返回去重后最后一個(gè)元素的地址,因?yàn)閡nique去除的是相鄰的重復(fù)元素,所以一般用之前都會(huì)要排一下序。
若調(diào)用sort后,vector的對(duì)象的元素按次序排列如下:
sort jumps over quick red red slow the the turtle則調(diào)用unique后,vector中存儲(chǔ)的內(nèi)容是:
注意,words的大小并沒(méi)有改變,依然保存著10個(gè)元素;只是這些元素的順序改變了。調(diào)用unique“刪除”了相鄰的重復(fù)值。給“刪除”加上引號(hào)是因?yàn)閡nique實(shí)際上并沒(méi)有刪除任何元素,而是將無(wú)重復(fù)的元素復(fù)制到序列的前段,從而覆蓋相鄰的重復(fù)元素。unique返回的迭代器指向超出無(wú)重復(fù)的元素范圍末端的下一個(gè)位置。
注意:算法不直接修改容器的大小。如果需要添加或刪除元素,則必須使用容器操作。
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()); //"刪除"相鄰的重復(fù)元素 20 assert(vector1.size()==N); 21 22 vector1.erase(new_end,vector1.end()); //刪除(真正的刪除)重復(fù)的元素 23 copy(vector1.begin(),vector1.end(),ostream_iterator<int>(cout," ")); 24 cout<<endl; 25 26 return 0; 27 }?
?
轉(zhuǎn)載于:https://www.cnblogs.com/fish7/p/4391035.html
總結(jié)
以上是生活随笔為你收集整理的STL 去重 unique的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [转]使用CSS3 Grid布局实现内容
- 下一篇: 历届试题 错误票据