平常的去重代码:
#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把后面藏着的元素删除了
另外,也可以实现vector的不排序去重:
方法是在遍历的时候,将相等的元素除第一个外,后面的统统作标记。如:一个字符序列,可以用数字0来标记。应该说,直接将0赋值给这个元素。然后通过另一个容器,在遍历原容器的同时,将没有做标记的元素Push_back 到新容器中。
这个就是利用vector把后面藏着的元素删除了