zoukankan      html  css  js  c++  java
  • unique

    作用

      元素去重,即“删除”序列中所有相邻的重复元素(只保留一个)

    (此处的删除,并不是真的删除,而是指重复元素的位置被不重复的元素占领了)

    (其实就是把多余的元素放到了最后面)

    由于它“删除”的是相邻的重复元素

    所以在使用unique函数之前,一般都会将目标序列进行排序

    (用unique之前,最好用个sort等排序来先把目标排个序)

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

    应用:

    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;
    }
  • 相关阅读:
    SpringMVC(二)
    SpringMVC(一)
    Mybatis之mapper.xml配置文件中的#{}和${}
    Mybatis(二)
    Mybatis(一)
    Linux部署项目
    BOS物流项目第十三天
    Failed to read schema document 'http://www.springframework.org/schema/beans/spring-beans.xsd'
    景点API支持查询携程旅游门票景点详情
    Html引入百度富文本编辑器ueditor及自定义工具栏
  • 原文地址:https://www.cnblogs.com/darlingroot/p/10397629.html
Copyright © 2011-2022 走看看