unique函数存在于#include <iostream>头文件中。
作用是求出相邻不重复序列的个数。此函数的返回值是首地址。
函数格式m=unique(a,a+n)-a;
比如a[5]={1,2,2,3,2},则输出m为4.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <queue>
#include <map>
#include <stack>
#include <list>
#include <vector>
using namespace std;
//define DEBUG
int a[1000];
int main()
{
#ifdef DEBUG
freopen("cin.txt", "r", stdin);
freopen("cout.txt", "w", stdout);
#endif
int n,i,m;
while (~scanf("%d",&n))
{
memset(a,0,sizeof(a));
for (i=0;i<n;i++)
scanf("%d",&a[i]);
m=unique(a,a+n)-a;
printf("%d\n",m);
}
return 0;
}
函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置
举例如下:
一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标
则
pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。
pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。
pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。
所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~
返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
int main()
{
int n;
const int size=5;
typedef vector <int> v;
v a(size);
a[0]=1;
a[1]=3;
a[2]=4;
a[3]=6;
a[4]=8;
v::iterator it;
for (it=a.begin();it!=a.end();it++)
cout<<*it<<" ";
cout<<endl;
while (~scanf("%d",&n))
{
int k=lower_bound(a.begin(),a.end(),n)-a.begin();
cout<<k<<endl;
}
return 0;
}
先用unique去重复,然后再进行排序查询。#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int n;
int a[10]={1,2,2,3,5,5,7,7,8,9};
int h=unique(a,a+10)-a;
for (int i=0;i<h;i++)
printf("%d ",a[i]);
while(~scanf("%d",&n))
{
int k=lower_bound(a,a+h,n)-a;
cout<<k<<endl;
}
}