二分查找比某个值小的元素的位置
Binary search for the position of the element that is just smaller that a value
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;
演示。
相关文章:
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 求最大元素位置的分治算法
- 如何将元素添加到向量的字符串位置
- 这个返回元素位置的基于循环的函数有什么问题?
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 数组中所有元素的最新最小元素的第五个位置
- 是否有任何优雅的方式来遍历元素位置可以更改的列表?
- 如何从几乎排序的链表中分离放错位置的元素?
- 如何获得相同数量的第一个和第二个元素以及它们在c++中各自的位置
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 这是查找向量中元素位置的合法方法吗?
- 用于在字符串(C )向量中找到元素位置的函数中的错误
- 如何比较和存储 2 个向量的数据元素位置
- 获取与特定模式距离最小的矢量的元素位置
- 最大 N 个等元素位置的 C++ 向量
- OpenCV 从矩阵中获取条件基最大元素位置
- 有没有一种方法可以从传递给排序的lambda中获取元素位置
- 标准::多集,跟踪插入的元素位置
- 在C++中指定数组声明中的元素位置
- 获取std::vector中的元素位置