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;
}