二分查找函数

#include<iostream>
#include<algorithm>
#include<vector>
#include<functional>
using namespace std;
int main()
{
    int a[]={4,10,11,30,30,69,70,96,100};
    int a2[]={30,69,70};
    int a3[]={30,50,70};
	vector<int> vec(a,a+9);
	vector<int> vec2(a2,a2+3);
	vector<int> vec3(a3,a3+3);
    int binary1=binary_search(vec.begin(),vec.end(),4);
    cout<<"在数组中查找元素4,结果为:"<<binary1<<endl;//查找成功,返回1
 
    int binary2=binary_search(vec.begin(),vec.end(),40);
    cout<<"在数组中查找元素40,结果为:"<<binary2<<endl;//查找失败,返回0
 
    int lower1=lower_bound(vec.begin(),vec.end(),10)-vec.begin();
    cout<<"在数组中查找第一个大于等于10的元素位置,结果为:"<<lower1<<endl;//返回1 
 
    int lower2=lower_bound(vec.begin(),vec.end(),101)-vec.begin();
    cout<<"在数组中查找第一个大于等于101的元素位置,结果为:"<<lower2<<endl;//返回9 
 
    int upper1=upper_bound(vec.begin(),vec.end(),10)-vec.begin();
    cout<<"在数组中查找第一个大于10的元素位置,结果为:"<<upper1<<endl;//返回2 
 
    int upper2=upper_bound(vec.begin(),vec.end(),101)-vec.begin();
    cout<<"在数组中查找第一个大于101的元素位置,结果为:"<<upper2<<endl;//返回9 
 
    auto bounds=equal_range(vec.begin(),vec.end(),30);
    int min=bounds.first-vec.begin();
    int max=bounds.second-vec.begin();
    cout<<"在数组中查找到的30所在的范围为"<<"["<<min<<","<<max<<")"<<endl;//返回[3,5)
 
    auto bounds2=equal_range(vec.begin(),vec.end(),100);
    min=bounds2.first-vec.begin();
    max=bounds2.second-vec.begin();
    cout<<"在数组中查找到的100所在的范围为"<<"["<<min<<","<<max<<")"<<endl;//返回[8,9)
 
    int include1=includes(vec.begin(),vec.end(),vec2.begin(),vec2.end());
    cout<<"在vec1中查找vec2,结果为:"<<include1<<endl; //查找成功,返回1 
 
    int include2=includes(vec.begin(),vec.end(),vec3.begin(),vec3.end());
    cout<<"在vec1中查找vec3,结果为:"<<include2<<endl; //查找失败,返回0 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值