Files
python/C++专题课程/STL基础知识/STL-9-Binary search详解.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

33 lines
1.2 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}