unique、unique_copy的用法

unique

源码:

tmplate<class ForwardIterator>
ForwardIterator unique(ForwardIterator first,ForwardIterator last)
{
  first = adjacent_find(first,last);
  return unique_copy(first,last,first);
}

 可以看出,unique在内部首先找到相邻重复的首位置,然后调用unique_copy将后续的元素覆盖到重复的元素上,所以容器中的元素个数并没有变化。其返回值是指向去重后新区间尾端的迭代器,在使用之前应先排序。如果输入1 1 2 3 3,它的输出是1 2 3 1 3。

sort(words.begin(), words.end()); 
vector<string>::iterator end_unique =  unique(words.begin(), words.end()); 
words.erase(end_unique, words.end());

 unique_copy

源码:

template <class InputIterator,class OutputIterator>
inline OutputIterator unique_copy(InputIterator first,InputIterator last,OutputIterator result)

 将[first,last)中的数据复制到result开头的区间中,如果元素重复则只复制一个,返回的迭代器指向以result开头的区间尾端。如果result用的容器和先前的容器不一样的话,需要使用result的插入型迭代器.

#include<iostream>
#include<list>
#include<vector>
#include<algorithm>
#include <iterator>
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中
	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;
}

 这里用到了插入型迭代器,可参看博客http://www.cnblogs.com/chinazhangjie/archive/2011/06/25/2090084.html

posted @ 2015-03-21 16:30  zhanghui_dut  阅读(156)  评论(0)    收藏  举报