一.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提供的效果,你就必须间接完成这个任务,但正如我在上面勾画的,会有不少选择。