STL 1.3 二分查找

从小到大排序的数组:

lower_bound

int i = lower_bound(nums, nums + n, a) - nums;

返回数组 nums 中大于等于 a 的第一个元素的地址/位置   数字个数:地址值(从0开始算)+1,若 nums 中的元素均小于 a 则返回尾后地址。

int nums[n]{ 1,2,5,7,9 };

int i = lower_bound(nums, nums + n, 6) - nums;   //大于等于6

cout << i << endl;    //i=3

upper_bound

int i = upper_bound(nums, nums + n, a) - nums;

返回第一个大于参数a的元素地址(故a到头 -1),否则返回了数组越界后的那一个元素的指针

equal_range()  找出搜寻值最佳插入位置

pair<_FwdIt, _FwdIt>

可认为是lower_bound和upper_bound的结合,

pair中的第一个迭代器由lower_bound返回, 第二个则由upper_bound返回.

binary_search  查找某个元素是否出现    数组需事先排好大小顺序
binary_search(arr[],arr[]+size,e)
arr[]:数组首地址
size:数组元素个数
e:需要查找的值
查找到e元素则真,若查找不到则返回值是假
 

本关任务:给定包含N个整数的无序序列S(a1​,a2​,..,aN​),以及M次查询序列Q(b1​,b2​,..,bM​),判定bj​是否在序列S中。

#include <iostream>

#include <algorithm>

using namespace std;

int main(int argc, const char * argv[]) {

     int n;

     cin>>n;

     int *a=new int [n];

     for(int i=0;i<n;i++){

         cin>>*(a+i);    //*(a+i)是指针指的变量,是数

     }

     sort(a,a+n);

    int m;

     cin>>m;

     for(int h=0;h<m;h++){

         int t;

         cin>>t;

         if(binary_search(a,a+n,t)){

             printf("%d in array\n",t);

         }

         else{

             printf("%d not in array\n",t);

         }

     }

    return 0;

}

输入:

7

2 5 9 5 5 3 1

 3

4 7 5

—— 预期输出 ——

4 not in array

7 not in array

5 in array

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值