使用方式
- 函数unique原形
iterator unique (iterator first, iterator last, pre);- 参数类型以及返回值都是迭代器
- 返回值: 是排序好的元素的最后一个元素位置
- 第三个比较方式:是判断什么条件两个是相同的,然后参照unique的函数板子进行操作
- 函数原型模板如下(类似官方使用,具体看参考地址):
iterator my_uniqu(iteraotr first, iitera last)
{
if(first == last) return last;
iterator result = first;
while(++first != last){
if( !(*result == * first) )
*(++result) =*first
}
return ++result;
}
result:代表的是不相同的元素的指标位置, first:代表的从前向后便利的指标, 其中while循环中的++first 代表元素后移动- 如果不相同,就将元素复制到result指向的后一个位置,所以是++result
- 最后
return ++result, 所以是元素的不相同的后一个位置
sort函数 + unique去重+ erase函数去数值
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1000;
int a[maxn];
int main()
{
int n;
cin >> n; //5 6 6 7 7 7 8 8 8 9
for(int i = 0 ;i <n;i++) cin >> a[i];
vector<int> v(a,a+n);
sort(a,a+n);
//开始去重
vector<int>::iterator it = unique(v.begin(),v.end());
cout << distance(v.begin(),it) << endl;
//进行擦除
v.erase(it,v.end());
for(it = v.begin();it != v.end();it++)
cout << (*it)<< " ";
cout <<endl;
return 0;
}
distance函数:返回的迭代器中元素的个数,也就是长度
自动写比较函数
pred:
Binary function that accepts two elements in the range as argument, and returns a value convertible to bool. The value returned indicates whether both arguments are considered equivalent (if true, they are equivalent and one of them is removed).
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
- 函数返回值bool
- 参数是两个元素的比较
- 如果为true相同,条件自定义
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1000;
int a[maxn];
bool cmp(int a, int b)
{
if(a + 1 == b) return true;
else return false;
}
int main()
{
int n;
cin >> n; //5 6 6 7 7 7 8 8 8 9
for(int i = 0 ;i <n;i++) cin >> a[i];
vector<int> v(a,a+n);
sort(a,a+n);
vector<int>::iterator it = unique(v.begin(),v.end(),cmp);
for(it = v.begin();it != v.end();it++)
cout << (*it)<< " ";
cout <<endl;
return 0;
}
输出: 5 7 7 7 9 7 8 8 8 9
5 6 6 7 7 7 8 8 8 9输入结果是如上,原因- 判断方法如上,其中不同的元素是
5 7 7 7 9 ,后面元素都是不变的 - 5与6同一个元素,所以第二个标记一直向后移动,知道数字7
- 此时5 + 1 != 7 ,所以保存了
7,result:指向的是7,first向后移动 first后面也是7,但是此时是不同,所以result能够保存数值,result继续赋值,直到数字9- 此时也不相同,所以元素完毕就是
参考来源:
- 讲的比较清楚的,推荐
https://www.cnblogs.com/wangkundentisy/p/9033782.html
- 官网
http://www.cplusplus.com/reference/algorithm/unique/
本文介绍了C++中unique函数的使用方法,包括其函数原型和返回值。通过结合sort和erase函数实现数值去重,并探讨了自定义比较函数的方式。文章还提供了相关参考链接以深入理解unique函数。
1027

被折叠的 条评论
为什么被折叠?



