Live2d Test Env

【整理】C++中的unique函数

之前总结了一下我觉得有用的erase,lower_bound,upper_bound。

  • 现在总结一下unique,unique的作用是“去掉”容器中相邻元素的重复元素(不一定要求数组有序),它会把重复的元素添加到容器末尾(所以数组大小并没有改变),而返回值是去重之后的尾地址,下面举个例子。
  • 由于返回的是容器末尾,所以如果想得到去重后的size,需要减去初始地址,lower_bound是得到地址,稍微不同。

如:

  sz = unique(b + 1,b + n + 1)-(b + 1);
  sz = unique(a,a + n) - a;

对比一下lower_bound:

  pos=lower_bound(b + 1,b + sz + 1,a[i]) - b;
  • 或许你会说可以直接模拟。通过再开一个数组,数字与前一个相同的相同的不加入新数组,仅仅多开了一个数组而已,不久搞定了吗。那么unique到底有什么优势呢?比如,假如要得到相邻不同的字符串组,用unique就方便些(好像模拟也不麻烦,就当为了“美”而用unique吧)。
sort(words.begin(), words.end()); 
vector<string>::iterator end_unique =  unique(words.begin(), words.end()); 
words.erase(end_unique, words.end());

 

  • 如果要删去重复元素,可以把尾巴删去即可(或者直接定义新的长度!)。
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
int main()
{
    const int N=11;
    int array1[N]={1,2,0,3,3,0,7,7,7,0,8};
    vector<int> vector1;
    for (int i=0;i<N;++i)
        vector1.push_back(array1[i]);

    vector<int>::iterator new_end;
    new_end=unique(vector1.begin(),vector1.end());    //"删除"相邻的重复元素
    assert(vector1.size()==N);

    vector1.erase(new_end,vector1.end());  //删除(真正的删除)重复的元素
    copy(vector1.begin(),vector1.end(),ostream_iterator<int>(cout," "));
    cout<<endl;

    return 0;
}

(代码当然是舶来品。。。)

posted @ 2017-12-01 18:33  nimphy  阅读(26614)  评论(0编辑  收藏  举报