12.3 - STL中的二分查找 - lower_bound、upper_bound

lower_bound 查找下界

在元素为任意T类型、按照自定义排序规则排好序的数组中进行查找

    T* lower_bound(数组名+n1,数组名+n2,值,排序规则结构名());

返回 T* p

*p是查找区间里,下标最小的,可以排在“值”后面的元素,如果找不到,p指向下标为n2的元素。//大于等于值

upper_bound 查找下界

在元素为任意T类型、按照自定义排序规则排好序的数组中进行查找

    T* upper_bound(数组名+n1,数组名+n2,值,排序规则结构名());

返回 T* p

*p是查找区间里,下标最小的,必须排在“值”后面的元素,如果找不到,p指向下标为n2的元素。//大于值

#include<iostream>
#include<algorithm>
using namespace std;
struct Rule1{
	bool operator()(const int &a1, const int &a2){
		return a1 % 10 < a2 % 10;
	}
};
void Print(int a[], int size){
	for (int i = 0; i < size; ++i){
		cout << a[i] << " ";
	}
	cout << endl;
}

int main(){
	int a[7] = { 12, 5, 3, 5, 98, 21, 7 };
	sort(a, a + 7, Rule1());
	Print(a, 7);
	cout << *lower_bound(a, a + 7, 16, Rule1()) << endl;
	cout << lower_bound(a, a + 7, 16, Rule1()) << endl;
	cout << lower_bound(a, a + 7, 16, Rule1()) - a << endl;
	cout << *upper_bound(a, a + 7, 5, Rule1()) << endl;
	cout << upper_bound(a, a + 7, 5, Rule1()) - a << endl;
	cout << *upper_bound(a, a + 7, 8, Rule1()) << endl;
	cin.get();
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值