c++ - 是否可以使用 lower_bound() 对普通结构数组进行二进制搜索?

标签 c++ stl

我在内存中有一个 16 字节宽条目的数组。每个条目由两个 64 位整数字段组成。这些条目根据每个条目的第一个 64 位整数的数值进行排序。是否可以在不首先将数据加载到 std::vector 的情况下使用 STL 进行二进制搜索?

我已经看到我可以在普通数组上使用 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 代替比较器的完整仿函数。

关于c++ - 是否可以使用 lower_bound() 对普通结构数组进行二进制搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11370794/

相关文章:

c++ - Dynamic_cast 未显示正确的对象类型

c++ - 这是向容器添加元素的正确方法吗?

c++ - 哪个是查找速度最快的 STL 容器?

c++ - 有序元素的最佳容器

c++ - 空时访问索引0处的 vector

c++ - 更改/添加 STL bitset<>::reference::operator=(int) 的行为

c++ - GLSL 错误 : failed to preprocess the source. 我该如何解决这个问题?

c++ - 构建 Qt - NMAKE : fatal error U1077: 'cd' : return code '0x2'

C++。如何将 const_cast 指针指向成员函数?

c++ - 使用指针在映射中释放内存