语法解释
这两个函数都是头文件<algorithm>
里面的,函数模板:
除了函数名,其他的都一样。
first last是迭代器,类似vector::iterator.
[first, last)是一个有序的序列,是这个函数负责查找的范围。
val就是要找上下限的那个值。
comp是一个比较函数:
实现原理
在一个有序序列中,二分查找。
重点
lower_bound返回第一个值大于等于(不小于)val的迭代器。如果所有值都比val小的话,返回last.
upper_bound返回第一个值大于val的迭代器。如果没有,返回last.
lower_bound
Returns an iterator pointing to the first element in the range[first, last) which does not compare less than val.
Unlike upper_bound, the value pointed by the iterator returned by this function may also be equivalent to val, and not only greater.
upper_bound
Returns an iterator pointing to the first element in the range[first, last) which compares greater than val.
Unlike lower_bound, the value pointed by the iterator returned by this function cannot be equivalent to val, only greater.
代码示例
// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
using namespace std;
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
sort (v.begin(), v.end());
// 10 10 10 20 20 20 30 30
// 0 1 2 3 4 5 6 7
vector<int>::iterator low,up;
low=lower_bound (v.begin(), v.end(), 20);
up= upper_bound (v.begin(), v.end(), 20);
cout << "lower_bound at position " << (low- v.begin()) << '\n';
cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
应用场景
比如这个题解的方法二。