C++ lower_bound()函数和upper_bound()函数

头文件<algorithm>

1、lower_bound(first,last,index):在位置first和last之间,返回大于或等于index的最小位置的地址
2、upper_bound(first,last,index):在位置first和last之间,返回大于index的最小位置的地址

实例

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int n,index,a[1010];
	cin>>n>>index;
	for(int i=0;i<n;i++)
		cin>>a[i];
	int van=lower_bound(a,a+n,index)-a;//返回的是大于或等于index的最小位置 
	//数组必须非递减
	int van1=upper_bound(a,a+n,index)-a;
	//返回大于index的最小位置,数组必须非递减 
	cout<<van<<endl;
	cout<<van1<<endl;
	return 0;
}

输入:
6 3
1 2 3 3 4 5
输出:
2
4

注:n为6,index为3,数组[1,2,3,3,4,5]中大于或等于3的位置为2,即数字3。大于3的位置为4,即数字4。

C++ 中,`lower_bound` `upper_bound` 是 `<algorithm>` 模块提供的两个算法,用于在一个已排序的容器(如向量、列表、集合等)中查找指定元素的位置。这两个函数都是模板函数,可以接受任意类型的比较器(比如默认的 `<` 运算符),以及迭代器作为输入。 1. **lower_bound**: - 函数原型:`template <class _RandomAccessIterator, class _Tp, class _Compare = less<_Tp>> _RandomAccessIterator lower_bound(_RandomAccessIterator first, _RandomAccessIterator last, const _Tp& value, _Compare comp = _Compare());` - 功能:返回一个指向第一个大于等于给定值 `value` 的元素的迭代器,如果序列中不存在这样的元素,则返回 `last`(即序列结尾)。 - 示例: ```cpp std::vector<int> vec = {1, 3, 4, 6, 8}; auto it = std::lower_bound(vec.begin(), vec.end(), 5); // it 现在指向值为 5 或者更大的元素的开始位置 ``` 2. **upper_bound**: - 函数原型:`template <class _RandomAccessIterator, class _Tp, class _Compare = less<_Tp>> _RandomAccessIterator upper_bound(_RandomAccessIterator first, _RandomAccessIterator last, const _Tp& value, _Compare comp = _Compare());` - 功能:返回一个指向第一个大于给定值 `value` 的元素的迭代器,如果序列中不存在这样的元素,则返回 `last + 1`(即序列结束后的下一个位置)。 - 示例: ```cpp std::vector<int> vec = {1, 3, 4, 6, 8}; auto it = std::upper_bound(vec.begin(), vec.end(), 5); // it 现在指向值为 6 或者更大的元素的开始位置 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值