C++ STL

本文深入讲解了二分查找算法中的lower_bound和upper_bound函数的使用方法及示例代码,同时介绍了binary_search函数的用途,帮助读者理解并掌握这些重要的搜索算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二分查找

  1. lower_bound
    (起始地址,结束地址,要查找的数值) 返回的是数值 第一个 出现的位置
    ( 返回大于等于val的值)

  2. upper_bound
    (起始地址,结束地址,要查找的数值) 返回的是数值 最后一个 出现的位置
    Returns an iterator pointing to the first element in the range [first,last) which compares greater than val.

example

// lower_bound/upper_bound example
#include <iostream>     // std::cout
#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort
#include <vector>       // std::vector

int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  std::vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20

  std::sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30

  std::vector<int>::iterator low,up;
  low=std::lower_bound (v.begin(), v.end(), 20); //          ^
  up= std::upper_bound (v.begin(), v.end(), 20); //                   ^

  std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
  std::cout << "upper_bound at position " << (up - v.begin()) << '\n';

  return 0;
}

结果
lower_bound at position 3
upper_bound at position 6

  1. binary_search
    (起始地址,结束地址,要查找的数值) 返回的是是否存在这么一个数,是一个bool值
    (binary_search (ForwardIterator first, ForwardIterator last, const T& val))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值