C++STL之二分搜索算法

/*
二分搜索算法
使用这些算法的前提:给定的序列为升序

lower_bound(beg,end,val)
lower_bound(beg,end,val,comp) //因对comp的作用机制不胜理解,暂不考虑使用
返回一个迭代器,表示的是键值为val的元素可以插入的第一个位置。
注意:C++Primer(第5版)中文版对该函数功能的描述有误!!!

upper_bound(beg,end,val)
upper_bound(beg,end,val,comp) //因对comp的作用机制不胜理解,暂不考虑使用
返回一个迭代器,表示的是键值为val的元素可以插入的最后一个位置。

lower_bound与upper_bound功能对比详解:
在序列里没有元素val的时候,两个元素的返回值是一样的。
1 2 4 5 这个序列,upper_bound(3)和lower_bound(3)都返回位置2(下标)

如果只有一个元素val,low返回那个元素的位置,而upper_bound返回那个元素的位置的后一个位置。
1 2 4 5 这个序列upper_bound(2)返回下标2而lower_bound(2)返回下标1

多个元素val,lower_bound返回那多个元素中的第一个的位置,upper_bound返回那多个元素中的最后一个的后一个位置。
1 2 2 4 5 这个序列 upper_bound(2)返回下标3的位置,lower_bound(2)返回下标1的位置。

注意:在一个升序里,如果所有元素都大于val,则upper_bound和lower_bound都返回begin。都小于val则返回end(越界了)。
*/
#include "stdafx.h"
#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
int a1[] = { 1,2,4,5 };
printf("lower_bound a1 %d\n", lower_bound(a1, a1 + 4, 3) - a1);
printf("lower_bound a1 %d\n", upper_bound(a1, a1 + 4, 3) - a1);

int a2[] = { 1,2,4,5 };
printf("lower_bound a2 %d\n", lower_bound(a2, a2 + 4, 2) - a2);
printf("lower_bound a2 %d\n", upper_bound(a2, a2 + 4, 2) - a2);

int a3[] = { 1,2,2,4,5 };
printf("lower_bound a3 %d\n", lower_bound(a3, a3 + 5, 2) - a3);
printf("lower_bound a3 %d\n", upper_bound(a3, a3 + 5, 2) - a3);

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值