注意
在使用自定义比较器时,两个函数的传参位置是相反的,函数返回规则也是相反的
传参位置详见底部用例
函数返回规则详见函数介绍
lower_bound()
Defined in header <algorithm>
(1)
//在 [first, last) 区域内查找不小于 value 的元素
template< class ForwardIt, class T >
ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value );
(2)
//在 [first, last) 区域内查找第一个 不符合 comp 规则的元素
template< class ForwardIt, class T, class Compare >
ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp );
upper_bound()
Defined in header <algorithm>
(1)
// 在 [first, last) 区域内查找大于 value 的元素
template< class ForwardIt, class T >
ForwardIt upper_bound( ForwardIt first, ForwardIt last, const T& value );
(2)
// 查找[first, last)区域中第一个 符合 comp 规则的元素
template< class ForwardIt, class T, class Compare >
ForwardIt upper_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp);
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> a= {1,1,1,2,2,2,3,3,3,4,4,4,5,5,5};
int value = 3;
auto p1 = upper_bound(a.begin(), a.end(), value);
cout << "第一个比3大的数为:" << *p1 << endl;
cout << "该元素下标为" << p1-a.begin() << endl;
auto p2 = lower_bound(a.begin(), a.end(), value);
cout << "第一个不大于3的数为:" << *p2 << endl;
cout << "该元素下标为" << p2-a.begin() << endl;
cout << endl;
auto p3 = upper_bound(a.begin(), a.end(), value, [&] (int value, int arrayElem) {return value < arrayElem;});
cout << "第一个比3大的数为:" << *p3 << endl;
cout << "该元素下标为" << p3-a.begin() << endl;
auto p4 = lower_bound(a.begin(), a.end(), value, [&] (int arrayElem, int value) {return arrayElem < value;});
cout << "第一个不大于3的数为:" << *p4 << endl;
cout << "该元素下标为" << p4-a.begin() << endl;
return 0;
}
// 输出结果如下
/*
第一个比3大的数为:4
该元素下标为9
第一个不大于3的数为:3
该元素下标为6
第一个比3大的数为:4
该元素下标为9
第一个不大于3的数为:3
该元素下标为6
*/