转载:https://blog.csdn.net/PolarAurora/article/details/76582743
STL中有这样的两个函数 lower_bound upper_bound函数
用于在非递减序列中查找元素
1、lower_bound函数:
1>用法:
lower_bound(起始位置,起始位置+查找的最大长度,查找的元素,(cmp))- 数组指针名(数组名)
2>解释:lower_bound(p,p+n,x)作用是在p[n]数组中查找大于或等于x的第一个位置,得到的结果是一个指针,前提是数组p[n]进行了排序;指向同一个数组的两个指针相减,结果为两个指针之间的元素数目;
2、upper_bound 就是插入到序列中最晚的那个位置
算法说明:
ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置。
ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)算法返回一个非递减序列[first, last)中的第一个大于值val的位置。
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
//练习熟悉用lower_bound与upper_bound;
const int N = 1005;
int a[N];
int main()
{
int n;
//输入n个元素
scanf("%d",&n);
//n为12
//输入1 1 2 2 2 3 3 3 4 4 4 4
for(int i = 0;i < n;++i)
{
scanf("%d",&a[i]);
}
int m;
while(~scanf("%d",&m))
{
int x = lower_bound(a,a + n,m) - a;
printf("lower_bound值:%d\n",x);
int y = upper_bound(a,a + n,m) - a;
printf("upper_bound值:%d\n",y);
}
return 0;
}
输出: