upper_bound 和 lower_bound返回值问题
因为笔者对这两个函数的返回值问题经常搞不清,因此写本篇博客学习一下,upper_bound和
lower_bound 使用的是二分查找,所有在使用二分查找解决问题的时候会经常用到。
(1)upper_bound 的源码实现:
template <class ForwardIterator, class T>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator it;
iterator_traits<ForwardIterator>::difference_type count, step;
count = std::distance(first,last);
while (count>0)
{
it = first; step=count/2; std::advance (it,step);
if (!(val<*it))
{ first=++it; count-=step+1; }
else count=step;
}
return first;
}
upper_bound返回一个迭代器指针,指向第一个大于val值的位置。如果没有元素大于val,则返回last。
(2)lower_bound 的源码实现:
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator it;
iterator_traits<ForwardIterator>::difference_type count, step;
count = distance(first,last);
while (count>0)
{
it = first; step=count/2; advance (it,step);
if
lower_bound返回一个迭代器指针,指向第一个大于等于val值的位置。如果所有元素都小于val,则返回last。
(3)代码实现比较:
#include <iostream>
#include <algorithm>
#include <vector>
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8);
std::sort (v.begin(), v.end());
std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20);
up= std::upper_bound (v.begin(), v.end(), 20);
std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
lower_bound at position 3
upper_bound at position 6
根据代码我们可以清楚的知道,lower_bound返回一个迭代器指针,指向第一个大于等于20的位置,即对应索引为3;而upper_bound返回一个迭代器指针,指向第一个大于20的位置,即对应索引为6。