STL unique使用问题
string strs[] = {"one","one","two","three","three","four"}; vector<string> vs(strs,strs+6); unique(vs.begin(),vs.end()); for(vector<string>::iterator vi = vs.begin();vi!=vs.end();vi++) cout << *vi << "\t;
为什么执行结果为 one two three four three four
查看unipue源码,unique以最高的效率实现相邻相同元素的赋值删除,容器中的元素数量没有改变,但元素的值发生了改变(绝大部分情况下),不保证重复元素排在容器尾部
template <class ForwardIterator>
ForwardIterator unique (ForwardIterator first, ForwardIterator last)
{
if (first==last) return last;
ForwardIterator result = first;
while (++first != last)
{
if (!(*result == *first)) // or: if (!pred(*result,*first)) for version (2)
*(++result)=*first;
}
return ++result;
}