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;
    }
  • 相关阅读:
    UVALive 7509 Dome and Steles
    HDU 5884 Sort
    Gym 101194H Great Cells
    HDU 5451 Best Solver
    HDU 5883 The Best Path
    HDU 5875 Function
    卡特兰数
    UVa 11729 Commando War 突击战
    UVa 11292 The Dragon of Loowater 勇者斗恶龙
    Spark Scala Flink版本对应关系
  • 原文地址:https://www.cnblogs.com/darlingroot/p/10397629.html
Copyright © 2011-2022 走看看