lower_bound() 给出意外的结果
lower_bound() giving unexpected result
我写了一个代码,我需要从平方数序列中找到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_bound
和std::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
。
相关文章:
- 尝试将字符串/字符转换为整数会产生意外结果
- RapidXML - 代码创建意外结果
- 类中静态函数C++意外结果
- 指针数组中的意外结果
- 使用指针访问数组元素时出现意外结果
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- C++:比较运算符>和字符串文本的意外结果
- 具有意外结果的 C++ 闭包
- yaml-cpp 比较的意外结果
- 每次都出现意外结果
- 在 Qt 中解析嵌套的 JSON 时出现意外结果(数组不存在)
- 如何避免 std::abs 的意外结果?
- 使用嵌套 if 语句的意外结果
- A ^= B ^= A ^= B;C# Visual Studio 中的意外结果
- 逻辑错误,我将获得意外结果
- 在 c++ 中使用异步的意外结果
- 从函数的返回值将元素C++存储到 std::vector 中时出现意外结果
- 执行递增和递减时"cout"链接会产生意外结果
- OpenCL - 内核方法返回意外结果
- C++使用 std::get_time 解析 YYMMDD ISO 8601 日期字符串会得到意外结果