1.unique()是C++标准库函数里面的函数,其功能是去除相邻的重复元素(注意一定是相邻元素,且只保留一个),所以使用前需要对数组进行排序
那它是怎么实现去重的呢?删除?
不是,它并没有将重复的元素删除,而是把重复的元素放到数组的最后面 藏起来 了
当把原长度的数组整个输出来就会发现
其实是:
其中 1 2 8 9 10就是去重后的数组,后面的8 9 9 9 10就被“藏起来”了
验证示例:
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;//另一种用法:含义是:对于长度为n的数组a,unique(a,a+n) - a返回的是去重后的数组长度k
for (int i = 0;i < n;++i)
{
printf("%d ",a[i]);
}
puts("");
}
结果:
2.原理:
原理就是不断的将后面不重复的元素覆盖前面重复的元素,并且返回最后一个不重复元素下一个元素的坐标的(迭代器),因为**end()**指向的是最后一个元素的下一个迭代器
原理代码:
iterator My_Unique (iterator first, iterator last)//两个参数都是迭代器
{
if (first==last)
return last; // 只有一个元素的情况
iterator result = first; // 从第一个元素开始
while (++first != last) // 直到最后一个元素
{
if (*result != *first) // 找到了一个不重复的元素
*(++result)=*first; // 覆盖前面的元素
}
return ++result; // 返回最后不重复元素的下一个元素的坐标的迭代器
}
3.示例:
#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() );//这里就是把后面“藏起来”的重复元素删除了。就是利用vector把后面藏着的元素删除了
for ( it = v.begin() ; it != v.end() ; it++ )
{
printf ("%d ", *it);
}
puts("");
}
return 0;
}
结果:
4.unique()另一种用法:
k = unique(a,a+n) - a;
含义是:对于长度为L的数组a,unique(a,a+n) - a返回的是去重后的数组长度k
示例:
#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;
}
结果: