unique() [c++去重函数]

原文地址
https://blog.csdn.net/tomorrowtodie/article/details/51907471
CF上的代码是开放的,常常就能看到本渣与大神们的差距

比如去重。。。

这是本鶸代码。。。。。。。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 100000;
int a[N+5];
int b[N+5];
int main()
{
    int n;
    while (cin>>n)
    {
        for (int i = 0;i < n;++i)
        {
            scanf("%d",&a[i]);
        }
        sort(a,a+n);
        b[0] = a[0];int k = 0;
        for (int i = 1;i < n;++i)//去重
        {
            if (a[i]!=a[i-1])
            {
                b[++k] = a[i];
            }
        }
        for (int i = 0;i <= k;++i)
        {
            printf("%d ",b[i]);
        }
        puts("");
    }
    return 0;
}

然而大神是这样写的:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 100000;
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);
        n = unique(a,a+n) - a;//关键的一句
        for (int i = 0;i < n;++i)
        {
            printf("%d ",a[i]);
        }
        puts("");
    }
    return 0;
}

unique()是C++标准库函数里面的函数,其功能是去除相邻的重复元素(只保留一个),所以使用前需要对数组进行排序
上面的一个使用中已经给出该函数的一个使用方法,对于长度为n数组a,unique(a,a+n) - a返回的是去重后的数组长度

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

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

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

while (cin>>n)
    {
        for (int i = 0;i < n;++i)
        {
            scanf("%d",&a[i]);
        }
        sort(a,a+n);
        int k = unique(a,a+n) - a;
        for (int i = 0;i < n;++i)
        {
            printf("%d ",a[i]);
        }
        puts("");
    }

上述代码就是去重后再把原数组输出,测试一下看看结果就懂了

其中 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把后面藏着的元素删除了


作者:Must_so
来源:CSDN
原文:https://blog.csdn.net/tomorrowtodie/article/details/51907471
版权声明:本文为博主原创文章,转载请附上博文链接!

博主小注
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43093454/article/details/84932602