是否可以使用 lower_bound() 对结构的普通数组进行二分搜索
Is it possible to use lower_bound() to binary search a plain array of structs?
我在内存中有一个 16 字节宽条目的数组。每个条目由两个 64 位整数字段组成。这些条目根据每个条目的第一个 64 位整数的数值按排序顺序排列。是否可以使用 STL 进行二进制搜索,而无需先将数据加载到 std::vector 中?
我已经看到我可以在普通数组上使用 STL lower_bound() 方法,但我需要它忽略每个条目的第二个 64 位字段。这可能吗?
您不需要使用 std::vector<>
,但如果您先将数据转换为正确的数据类型,这是最简单的:
#include <cstdint>
struct mystruct
{
std::int64_t first, second;
};
您的问题不清楚您现在存储这些数据的方式,但我假设它类似于上述内容。
然后,您可以重载数据类型的operator<
:
#include <algorithm>
bool operator <(mystruct const& ms, std::int64_t const i)
{
return ms.first < i;
}
int main()
{
mystruct mss[10] = { /*populate somehow*/ };
std::int64_t search_for = /*value*/;
mystruct* found = std::lower_bound(mss, mss + 10, search_for);
}
或者您可以定义一个自定义比较器并将其传递给std::lower_bound
:
#include <algorithm>
struct mystruct_comparer
{
bool operator ()(mystruct const& ms, std::int64_t const i) const
{
return ms.first < i;
}
};
int main()
{
mystruct mss[10] = { /*populate somehow*/ };
std::int64_t search_for = /*value*/;
mystruct* found = std::lower_bound(mss,
mss + 10,
search_for,
mystruct_comparer());
}
当然,在 C++11 中,可以使用 lambda 代替比较器的完整函子。
struct Foo {
int64_t lower;
int64_t upper;
};
Foo arr[N];
Foo f;
f.lower = 42;
auto it = std::lower_bound(arr, arr + N, f,
[](const Foo& lhs, const Foo& rhs){ return lhs.lower < rhs.lower; });
是的,这是可能的。您需要创建一个满足 ForwardIterator 要求的类,该类以正确的方式迭代您的元素(16 字节结构的指针可能会解决问题)。然后,您需要定义自己的比较以比较忽略第二个 64 位字段的元素。更多信息。
template <class ForwardIterator, class T, class Compare>
ForwardIterator lower_bound ( ForwardIterator first, ForwardIterator last,
const T& value, Compare comp );
相关文章:
- 在对象数组中搜索字符串并返回相应值的函数
- 变量未在此范围内声明 数组线性搜索
- 从数组中搜索元素的索引
- 在数组中搜索复杂度高于 O(n) 的元素
- 如何在数组中搜索之前已输入的 int 值
- 如何在Char数组中搜索Char在IF条件语句中
- 如何在多维数组中搜索单个行,然后对某些行中的每个单个元素执行计算
- 如何编写一个 void 函数,该函数将在数组中搜索值,并通过引用将该值的位置传递回 main 函数
- 在排序静态数组中搜索的最快方法
- 在数组中搜索字符串的所有术
- 如何在结构中的数组中搜索
- 在数组中搜索以及搜索和遍历树
- 要求用户在数组中搜索一个整数
- 如何在2D数组中搜索以确保不超过3个连续字符
- 如何在 C++ 中的字符串数组中搜索字符串
- 如何在数组中搜索字符串
- 布尔查找函数未在数组中搜索
- C++ 如何在结构数组中搜索
- 在数组中搜索字符串
- 数组和搜索它们