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)) // or: if (!comp(val,*it)), for version (2)
{ first=++it; count-=step+1; }
else count=step;
}
return first;
}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 (*it<val) { // or: if (comp(*it,val)), for version (2)
first=++it;
count-=step+1;
}
else count=step;
}
return first;
}若val在原数组中存在,则upper_bound返回最后一个val的位置,lower_bound返回第一个val的位置
若val在原数组中不存在,则upper_bound和lower_bound返回的都是val因放在哪个位置而不影响原序列
本文详细解析了upper_bound与lower_bound算法的源码实现,介绍了这两种算法如何在已排序序列中查找特定值的位置。upper_bound定位的是大于给定值的第一个元素的位置,而lower_bound定位的是不小于给定值的第一个元素的位置。

1492

被折叠的 条评论
为什么被折叠?



