lower_bound() 给出意外的结果

lower_bound() giving unexpected result

本文关键字:意外 结果 bound lower      更新时间:2023-10-16

我写了一个代码,我需要从平方数序列中找到lower_bound。但是下限给了我upper_bound的结果。

这是我的代码和编译器链接:http://cpp.sh/3cppb

// Example program
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::vector<int> v{ 1, 4, 9, 16, 25 }; // all the square numbers

int x = std::lower_bound(v.begin(), v.end(), 5) - v.begin() ;

std:: cout<<"Postion "<<x<< "  value  "<<v[x] <<std::endl; //getting output for upperbound

}

输出:

Postion 2  value  9

预期输出

Postion 1  value  4
std::lower_bound

将迭代器返回到大于或等于目标值的第一个元素:

返回指向区域 [first, last(不小于(即大于或等于(值,或 last 如果未找到此类元素。

由于9是大于或等于5的第一个值(当然,它更大(,因此结果是完全正确的。

如果你试图找到一个已经在v中的元素,比如9,那么你会得到不同的结果std::lower_boundstd::upper_bound

std::distance(begin(v), std::lower_bound(begin(v), end(v), 9)); // 2
std::distance(begin(v), std::upper_bound(begin(v), end(v), 9)); // 3

std::lower_bound工作正常。 该函数返回不小于提供的值的第一个元素。 由于 9 是不小于 5 的第一个值,因此您可以获得该元素。

在这种情况下,std::upper_bound将返回与返回大于指定值的第一个元素相同的元素。 您将看到差异的地方是以下情况

std::vector data = {4,4,4};
auto low = std::lower_bound(data.begin(), data.end(), 4);
auto high = std::upper_bound(data.begin(), data.end(), 4);

在这种情况下,low将被begin(),因为 4 不小于 4,而high将被end(),因为向量中没有大于 4 的元素。

引用自标准,[lower.bound]:

template<class ForwardIterator, class T> ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value);

返回:在范围内i最远的迭代器[first,last]使得对于[first,i)范围内的每个迭代器j,以下相应的条件成立:*j < value