You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
1.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include<bits/stdc++.h>
using namespace std;
/*
知识点内容STL Binary search详解
以前遇到二分的题目都是手动实现二分,不得不说错误比较多,关于返回值,关于区间的左闭右开等很容易出错,
最近做题发现直接使用STL中的二分函数方便快捷还不会出错不过对于没有接触过的同学二分函数确实是一个头疼的部分
自己查的内容又有点乱,找不到具体的使用方法,有必要自己总结一份完整的以后备用。
文档内容参考:
https://www.cnblogs.com/aiguona/p/7281856.html
*/
using namespace std;
int main()
{
int a[100]= {4,10,11,30,69,70,96,100};
int b=binary_search(a,a+9,4);//查找成功返回1
cout<<"在数组中查找元素4结果为"<<b<<endl;
int c=binary_search(a,a+9,40);//查找失败返回0
cout<<"在数组中查找元素40结果为"<<b<<endl;
int d=lower_bound(a,a+9,10)-a;
cout<<"在数组中查找第一个大于等于10的元素位置结果为"<<d<<endl;
int e=lower_bound(a,a+9,101)-a;
cout<<"在数组中查找第一个大于等于101的元素位置结果为"<<e<<endl;
int f=upper_bound(a,a+9,10)-a;
cout<<"在数组中查找第一个大于10的元素位置结果为"<<f<<endl;
int g=upper_bound(a,a+9,101)-a;
cout<<"在数组中查找第一个大于101的元素位置结果为"<<g<<endl;
}