日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

STL 去重 unique

發(fā)布時間:2025/3/14 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 STL 去重 unique 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一.unique函數(shù)

類屬性算法unique的作用是從輸入序列中“刪除”所有相鄰的重復(fù)元素

該算法刪除相鄰的重復(fù)元素,然后重新排列輸入范圍內(nèi)的元素,并且返回一個迭代器(容器的長度沒變,只是元素順序改變了),表示無重復(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ù)是一個去重函數(shù), unique的功能是去除相鄰的重復(fù)元素(只保留一個),其實它并不真正把重復(fù)的元素刪除,是把重復(fù)的元素移到后面去了,然后依然保存到了原數(shù)組中,然后 返回去重后最后一個元素的地址,因為unique去除的是相鄰的重復(fù)元素,所以一般用之前都會要排一下序。

若調(diào)用sort后,vector的對象的元素按次序排列如下:

sort jumps over quick red red slow the the turtle

則調(diào)用unique后,vector中存儲的內(nèi)容是:

注意,words的大小并沒有改變,依然保存著10個元素;只是這些元素的順序改變了。調(diào)用unique“刪除”了相鄰的重復(fù)值。給“刪除”加上引號是因為unique實際上并沒有刪除任何元素,而是將無重復(fù)的元素復(fù)制到序列的前段,從而覆蓋相鄰的重復(fù)元素。unique返回的迭代器指向超出無重復(fù)的元素范圍末端的下一個位置。

注意:算法不直接修改容器的大小。如果需要添加或刪除元素,則必須使用容器操作。

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的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。