STL中关于二分查找的函数有3个
lower_bound,
upper_bund,
binary_search.
运用于有序区间
binary_search试图在已排序的[first,last)中寻找元素value,若存在就返回true,若不存在则返回false。
其中如果寻找的value存在,那么lower_bound返回一个迭代器指向其中第一个这个元素。upper_bound返回一个迭代器指向其中最后一个这个元素的下一个位置
(明确点说就是返回在不破坏顺序的情况下,可插入value的最后一个位置)。
如果寻找的value不存在,那么lower_bound和upper_bound都返回“假设这样的元素存在时应该出现的位置”。要指出的是lower_bound和upper_bound在源码中只是变换了if—else语句判定条件的顺序,就产生了最终迭代器位置不同的效果。
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;
int main()
{
int a[]={1,2,3,3,3,4,5};
cout<<lower_bound(a,a+5,3)-a<<endl; //别忘记-a
cout<<upper_bound(a,a+5,3)-a<<endl;
cout<<binary_search(a,a+5,6)<<endl;
return 0;
}