c++ - C++ std::binary_search() 和 std::lower_bound() 组合是否意味着我要进行两次二进制搜索?

标签 c++ c++11 vector iterator binary-search

在我使用二进制搜索在 vector 中快速查找元素的搜索中,我找到了 std::binary_search 函数,但后来意识到它只返回一个 bool 值,这让我很沮丧。

但后来我发现以这种方式查找元素的最常见解决方案是将 binary_search() 与 lower_bound() 配对。仔细观察后,我认为 lower_bound() 也使用二进制搜索式的情况搜索元素。那么,这是否意味着我正在搜索它两次?

这是我所指的示例: std::vector haystack{ 1, 3, 4, 5, 9 }; int 针 = 5;

if (std::binary_search(haystack.begin(), haystack.end(), needle)) {
    std::cout << "Found " << needle << '\n';

    std::vector<int>::iterator it = lower_bound(haystack.begin(), haystack.end(), needle);

    int result = *it;

    cout << "Result " << result << endl;
}

我是不是做错了?有没有另一种方法可以对 vector 中的某些内容进行二进制搜索并获取实际找到的元素?

最佳答案

是的,您正在进行两次二进制搜索。只需使用一次 lower_bound 进行额外比较:

auto it = std::lower_bound(haystack.begin(), haystack.end(), needle);
if (it != haystack.end() && *it == needle) {
    // found it, here.
}

但只有在需要迭代器时才这样做。如果您只想检查 needle 是否存在,我会使用 std::binary_search() 来为您的用户增加清晰度。这可以很好地根据 lower_bound 开始实现。来自 cppreference :

template<class ForwardIt, class T>
bool binary_search(ForwardIt first, ForwardIt last, const T& value)
{
    first = std::lower_bound(first, last, value);
    return (!(first == last) && !(value < *first));
}

关于c++ - C++ std::binary_search() 和 std::lower_bound() 组合是否意味着我要进行两次二进制搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26952844/

相关文章:

c++:一个程序来找到非常高的数字的平均值?

C++ 和调用栈——它可以用来获取行号吗?

c++11 - 将 IP 地址从 std::string 转换为 boost::uint32

c++:const_iterator 和 for-each 循环

c++ - 链表/vector 中的指针

C++:如何读取和写入文件夹

C++ - 你能假设 type* = std::array<type>::iterator 吗?

c++ - const auto 和 auto const 如何应用于指针?

c++ - Vector::at 与 vector::operator[]——不同的行为

c++ - cmake 无法在自定义位置或库存位置找到 boost