unique

unique()是C++标准库函数里面的函数,其功能是去除相邻的重复元素(只保留一个),所以使用前需要对数组进行排序

n = unique(a,a+n) - a;

上面的一个使用中已经给出该函数的一个使用方法,对于长度为n数组a,unique(a,a+n) - a返回的是去重后的数组长度

那它是怎么实现去重的呢?删除?

不是,它并没有将重复的元素删除,而是把重复的元素放到数组的最后面藏起来了

当把原长度的数组整个输出来就会发现:

其中 1 2 8 9 10就是去重后的数组,我这里把后面“藏起来”的数也输出了,方便理解

 

#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 1000;
int a[N + 5];
int main()
{
    int n;
    while (cin >> n)
    {
        for (int i = 0;i < n;++i) scanf("%d",&a[i]);
        sort (a, a + n);
        vector<int>v (a, a + n);
        vector<int>::iterator it = unique (v.begin(), v.end() );
        v.erase (it, v.end() );//这里就是把后面藏起来的重复元素删除了
        for ( it = v.begin() ; it != v.end() ; it++ )
        {
            printf ("%d ", *it);
        }
        puts("");
    }
    return 0;
}

 

 

这个就是利用vector把后面藏着的元素删除了

posted @ 2019-10-07 13:46  攒一兜星星*  阅读(416)  评论(0编辑  收藏  举报