lower_bound()返回一个 iterator 它指向在[first,last)标记的有序序列中可以插入value,而不会破坏容器顺序的第一个位置,而这个位置标记了一个不小于value 的值[1] 。该函数为C++ STL内的函数。
一个数组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,所以返回最后一个元素的下一个元素)。
/*
查找输入数字的排序好的数组位置
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int main()
{
int n;
int a[10]={12,18,13,24,35,98,75,14,78};
sort(a,a+10);
scanf("%d",&n);
int p=lower_bound(a,a+10,n)-a;
cout<<p<<endl;
/*if(a[p]==n)
cout<<n<<"地址查找正确在:"<<p+1<<endl;*/
return 0;
}
调用lower_bound之前必须确定序列为有序序列,否则调用出错。第一个版本排序根据底层的 <(小于)操作符,第二个版本根据comp进行排序。