这是一个去重函数,去除相邻元素的重复元素,由于是相邻元素,因此使用前一般要对元素进行排序(排序可以用到sort函数)。这里的“去除”并不是将元素删除掉,而是后面不重复的元素向前移动,将重复元素覆盖。例如数字:1 ,3 , 3, 4, 5,6 , 6 , 7 经过去重之后变为1,3,4,5,6,7,6,7
元素的个数并没有改变。
函数原型:(两个参数的情况)
iterator unique(iterator it_1,iterator it_2);
返回值为一个迭代器,指向不重复元素的下一个元素,对于上一个例子来说,返回指向6的迭代器(这个6是第七个数)。
可以结合vector将重复元素删除,这里要用到erase函数(题目超链接有dalao代码hhhh)
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int n=8;//数组长度
int num[8]={1,3,3,4,5,6,6,7};
vector<int>v;
for(int i=0;i<n;i++)
v.push_back(num[i]);
vector<int>::iterator it=v.begin();
sort(it,it+n);//先排序
cout<<"去重前的数组元素为:"<<endl;
for(int i=0;i<8;i++)
cout<<v[i]<<" ";
cout<<endl;
vector<int>::iterator new_it;
new_it=unique(it,it+8);//去重,返回指向6的迭代器
cout<<"去重后的数组元素为:"<<endl;
for(int i=0;i<8;i++)
cout<<v[i]<<" ";
cout<<endl;
v.erase(new_it,it+8);
cout<<"删除重复元素后的数组元素为:"<<endl;
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
cout<<endl;
}
输出结果为:
相同点:都是通过二分查找在一个排好序的数组中实现的(默认是升序排列)
不同点:
lower_bound函数是查找数组中第一个大于或等于给定值的元素,找到之后返回该元素的地址。没找到则返回end
upper_bound函数是查找数组中第一个大于给定值的元素,找到之后返回该元素的地址。没找到返回end
( lower_bound(num,num+8,4)-num 后面减去num得到的是找到的元素的下标,因为数组名也是指向数组第一个元素的指针嘛~ )
由于两个函数都是默认升序排列,以下代码是可以的:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int num[8]={1,1,2,3,4,4,4,6};//升序
cout<<lower_bound(num,num+8,4)-num<<endl;//输出:4
cout<<upper_bound(num,num+8,4)-num<<endl;//输出:7
cout<<lower_bound(num,num+8,6)-num<<endl;//输出:7
cout<<upper_bound(num,num+8,6)-num<<endl;//输出:8
cout<<lower_bound(num,num+8,0)-num<<endl;//输出:0
cout<<upper_bound(num,num+8,0)-num<<endl;//输出:0
}
然而如果数组降序排列,由于两个函数都是用二分查找,假如在数组{6,4,4,4,3,2,1,1}中查找4,二分查找mid指向3,发现3小于4,则要向右半部分查找,然而降序排列右半部分的元素肯定小于等于3,因此找不到4,只能返回end
代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[8]={6,4,4,4,3,2,1,1};//降序
cout<<lower_bound(a,a+8,4)-a<<endl;//输出:8
cout<<upper_bound(a,a+8,4)-a<<endl;//输出:8
cout<<lower_bound(a,a+8,6)-a<<endl;//输出:8
cout<<upper_bound(a,a+8,6)-a<<endl;//输出:8
cout<<lower_bound(a,a+8,0)-a<<endl;//输出:0
cout<<upper_bound(a,a+8,0)-a<<endl;//输出:0
}
当数组为降序的时候,也可以使用这两个函数,需要对这两个函数进行重载:
lower_bound( begin,end,num,greater<type>() ) //查找第一个小于等于num的元素
upper_bound( begin,end,num,greater<type>() ) //查找第一个小于num的元素
举个例子:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[8]={6,4,4,4,3,2,1,1};//降序
cout<<lower_bound(a,a+8,4,greater<int>())-a<<endl;//输出:1
cout<<upper_bound(a,a+8,4,greater<int>())-a<<endl;//输出:4
cout<<endl;
}