lower_bound upper_bound in C++

本文介绍了C++标准库函数lower_bound与upper_bound的用法及区别。它们用于在一个有序区间内查找特定值的位置,前者返回第一个不小于目标值的位置,后者返回第一个大于目标值的位置。通过示例代码展示了如何使用这两个函数。

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

语法解释

这两个函数都是头文件<algorithm>里面的,函数模板:
在这里插入图片描述
除了函数名,其他的都一样。
first last是迭代器,类似vector::iterator.
[first, last)是一个有序的序列,是这个函数负责查找的范围。
val就是要找上下限的那个值。
comp是一个比较函数:
在这里插入图片描述

实现原理

在一个有序序列中,二分查找。

重点

lower_bound返回第一个值大于等于(不小于)val的迭代器。如果所有值都比val小的话,返回last.
upper_bound返回第一个值大于val的迭代器。如果没有,返回last.
lower_bound
Returns an iterator pointing to the first element in the range[first, last) which does not compare less than val.
Unlike upper_bound, the value pointed by the iterator returned by this function may also be equivalent to val, and not only greater.
upper_bound
Returns an iterator pointing to the first element in the range[first, last) which compares greater than val.
Unlike lower_bound, the value pointed by the iterator returned by this function cannot be equivalent to val, only greater.

代码示例

// lower_bound/upper_bound example
#include <iostream>     // std::cout
#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort
#include <vector>       // std::vector
using namespace std;
int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20

  sort (v.begin(), v.end());                
  // 10 10 10 20 20 20 30 30
  //  0  1  2  3  4  5  6  7

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

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

  return 0;
}

应用场景

比如这个题解的方法二

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值