在矢量中查找项目
Seek item within vector
我有一个实数向量,按升序排序。
这些值可以在[0, 1]
的范围内。然后我在这个范围内选择一个值x
,我需要找到哪个是大于或等于x
的较小值的索引。
我可以通过在整个阵列上迭代来解决这个问题:
vector<double> values;
double x;
for (auto val : values)
{
if (x <= values)
{
// found
break;
}
}
有没有更快的方法可以得到同样的结果?我在考虑二进制搜索,但是如何实现呢?
使用std::lower_bound
:
#include <iterator>
#include <algorithm>
std::distance(begin(values)
, std::lower_bound(begin(values), end(values), x));
如果该项不存在,它将为您提供一个比上一个元素大一的索引。
DEMO
函数lower_bound可能会满足您的需求,您可以像下面这样使用它:
iter =lower_bound(values.begin(),values.end(),x);
您可以像数组一样使用运算符[]直接访问向量中的项,而不是使用迭代器从头开始。我想你已经知道二进制搜索了。在数组中实现它是你可以在任何地方找到的东西,所以我不会在这里向你解释。只需将向量视为数组即可。
你知道SO不是一个你要求别人给你写代码的网站,所以以std::binary_search为例,让你的方式:
// binary_search example
#include <iostream> // std::cout
#include <algorithm> // std::binary_search, std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
int main () {
int myints[] = {1,2,3,4,5,4,3,2,1};
std::vector<int> v(myints,myints+9); // 1 2 3 4 5 4 3 2 1
// using default comparison:
std::sort (v.begin(), v.end());
std::cout << "looking for a 3... ";
if (std::binary_search (v.begin(), v.end(), 3))
std::cout << "found!n"; else std::cout << "not found.n";
// using myfunction as comp:
std::sort (v.begin(), v.end(), myfunction);
std::cout << "looking for a 6... ";
if (std::binary_search (v.begin(), v.end(), 6, myfunction))
std::cout << "found!n"; else std::cout << "not found.n";
return 0;
}
正如Piotr所说,这不会给你指数,而是一个是/否的答案。然而,这应该是最简单的方法,因此也是最快的方法。
相关文章:
- 查找项目在哈希表中的位置
- 如何在Cmake中正确查找头路径,以便在我的项目中构建Box2D
- Visual Studio 2015资源视图和资源编译器使用不同的方法在项目目录中查找图标文件.如何修复
- 在5d映射C++中查找项目
- 通过查找一对项目的代码获取错误的输出,在给定的总和相等的给定列表中列表
- 查找两个 3 位数字的乘积(欧拉项目 #4)
- 更改 std::set 以按 T 类型查找项目
- C 使用字符串项目在列表中查找结构
- unordered_map仅查找先前找到的项目之后的项目
- 使用STD ::查找从向量中选择项目
- STD :: MAP-如何查找或添加,然后可以在一次搜索中删除项目
- 从项目名称查找 API 中查找项目
- 在给定键 (C++) 的地图向量内查找项目
- 如何在助推向量中查找项目
- 如何在 std::vector 中查找项目的位置
- 根据世界位置查找一维数组中的通用项目
- 如何在场景中查找项目
- 如何检查/查找项目是否在DEQUE中
- 在矢量中查找项目
- 如何在ublas::矩阵中查找项目的所有出现项