C++理解upper_bound 和lower_bound

本文介绍了C++中用于排序数组的upper_bound和lower_bound函数,通过名字含义帮助理解其功能:upper_bound找到大于等于目标值的插入位置,而lower_bound找到小于等于目标值的插入位置。举例说明了两者在查找过程中的应用。
摘要由CSDN通过智能技术生成

C++中的upper_bound 和lower_bound比较容易弄混。记住的方法是根据名字记住其功能,如upper_bound表示以某个数为上限,这个数应该放在哪个位置;lower_bound表示以某个数为下限,这个数应该放在哪个位置。同时注意数组应该提前拍好序。

举个例子:


#include<bits/stdc++.h>
using namespace std;
int main() {
  int a[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};
 
  cout << (lower_bound(a, a + 12, 4) - a) << endl; //输出 9
  cout << (upper_bound(a, a + 12, 4) - a) << endl; //输出 12
  cout << (lower_bound(a, a + 12, 1) - a) << endl; //输出 0
  cout << (upper_bound(a, a + 12, 1) - a) << endl; //输出 3
  cout << (lower_bound(a, a + 12, 3) - a) << endl; //输出 6
  cout << (upper_bound(a, a + 12, 3) - a) << endl; //输出 9
  cout << (lower_bound(a, a + 12, 5) - a) << endl; //输出 12
  cout << (upper_bound(a, a + 12, 5) - a) << endl; //输出 12
  cout << (lower_bound(a, a + 12, 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值