二分查找比某个值小的元素的位置

Binary search for the position of the element that is just smaller that a value

本文关键字:元素 位置 二分查找      更新时间:2023-10-16

c++新手到!给定一个排序向量v(非唯一值)和一个标量x,如何执行二进制搜索并返回等于或小于x的元素的位置?

std::vector<double> v { 0.9,0.78,0.6,0.4,0.33,0.2,0.2,0.2,0.07 }
double x = 0.7;
int position = BinaryFindPosition(v.begin(),v.end(),x);
// position is 2

使用std::lower_bound。请注意,由于矢量顺序从大到小,您应该使用rbegin()rend(),而不是begin()end():

std::vector<double> v { 0.9, 0.78, 0.6, 0.4, 0.33, 0.2, 0.2, 0.2, 0.07 };
double x = 0.7;
auto pos = std::distance(std::lower_bound(v.rbegin(), v.rend(), x), v.rend());
cout << pos << endl;

演示。