c++ - lower_bound() 给出意想不到的结果
问题描述
我写了一个代码,我需要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
, like中的元素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
推荐阅读
- javascript - 使用 ReactJS 设置输入时出错,material.ui 上没有非标签字段
- c++ - std::vector 的结构是什么?
- azure - Azure B2C - 我们需要为每个单独的客户创建一个 B2C 租户还是为所有客户创建一个 B2C 租户?最佳做法是什么?
- c# - .NETFramework Omnisharp Linux
- javascript - react js组件中的返回错误或三元运算符
- html - 如何制作 div 元素的图案
- barcode - 将 Pharmacode 添加到 PyZbar
- python - SQL 数据仅获取一次
- google-cloud-platform - 在 Dataproc 上运行的 Flink 作业未找到 Google 应用程序默认凭据
- android - 如何更改某个区域的图像视图的透明度?