离散化 unique eraser

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值