一.unique函數ios
類屬性算法unique的做用是從輸入序列中「刪除」全部相鄰的重複元素。算法
該算法刪除相鄰的重複元素,而後從新排列輸入範圍內的元素,而且返回一個迭代器(容器的長度沒變,只是元素順序改變了),表示無重複的值範圍得結束。數組
// sort words alphabetically so we can find the duplicates sort(words.begin(), words.end()); /* eliminate duplicate words: * unique reorders words so that each word appears once in the * front portion of words and returns an iterator one past the unique range; * erase uses a vector operation to remove the nonunique elements */ vector<string>::iterator end_unique = unique(words.begin(), words.end()); words.erase(end_unique, words.end());
在STL中unique函數是一個去重函數, unique的功能是去除相鄰的重複元素(只保留一個),其實它並不真正把重複的元素刪除,是把重複的元素移到後面去了,而後依然保存到了原數組中,而後 返回去重後最後一個元素的地址,由於unique去除的是相鄰的重複元素,因此通常用以前都會要排一下序。app
2、unique_copy函數函數
算法標準庫定義了一個名爲unique_copy的函數,其操做相似於unique。spa
惟一的區別在於:前者接受第三個迭代器實參,用於指定複製不重複元素的目標序列。code
unique_copy根據字面意思就是去除重複元素再執行copy運算。對象
編寫程序使用unique_copy將一個list對象中不重複的元素賦值到一個空的vector對象中。blog
//使用unique_copy算法 //將一個list對象中不重複的元素賦值到一個空的vector對象中 #include<iostream> #include<list> #include<vector> #include<algorithm> using namespace std; int main() { int ia[7] = {5 , 2 , 2 , 2 , 100 , 5 , 2}; list<int> ilst(ia , ia + 7); vector<int> ivec; //將list對象ilst中不重複的元素複製到空的vector對象ivec中 //sort(ilst.begin() , ilst.end()); //不能用此種排序,會報錯 ilst.sort(); //在進行復制以前要先排序,切記 unique_copy(ilst.begin() , ilst.end() , back_inserter(ivec)); //輸出vector容器 cout<<"vector: "<<endl; for(vector<int>::iterator iter = ivec.begin() ; iter != ivec.end() ; ++iter) cout<<*iter<<" "; cout<<endl; return 0; }
引用《Effective STL》中的:排序
咱們總結一下你的排序選擇:
● 若是你須要在vector、string、deque或數組上進行徹底排序,你可使用sort或stable_sort。
● 若是你有一個vector、string、deque或數組,你只須要排序前n個元素,應該用partial_sort。
● 若是你有一個vector、string、deque或數組,你須要鑑別出第n個元素或你須要鑑別出最前的n個元素,而不用知道它們的順序,nth_element是你應該注意和調用的。
● 若是你須要把標準序列容器的元素或數組分隔爲知足和不知足某個標準,你大概就要找partition或stable_partition。
● 若是你的數據是在list中,你能夠直接使用partition和stable_partition,你可使用list的sort來代替sort和stable_sort。若是你須要partial_sort或nth_element提供的效果,你就必須間接完成這個任務,但正如我在上面勾畫的,會有不少選擇。