前提: 既然是二分法,那么查找的数组肯定要保证有序
参数:
1.查找数组的首地址(一般都是数组名,如果是容器就是begin())
2.查找数组的尾地址(一般都是数组名+个数,如果是容器就是end())
3.查找的数字
lower_bound()函数:
返回值:第一次出现大于等于查找的数的地址
upper_bound()函数:
返回值:第一次出现大于查找的数的地址
示例:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[]={0,1,2,3,4,5,6}; // 7个数
cout<<"第一个大于等于2的数"<<*lower_bound(a,a+7,2)<<endl;
cout<<"第一个大于等于2的位置"<<lower_bound(a,a+7,2)-a<<endl;
cout<<"第一个大于 2的数"<<*upper_bound(a,a+7,2)<<endl;
cout<<"第一个大于 2的位置"<<upper_bound(a,a+7,2)-a<<endl;
return 0;
}