【问题标题】:std::binary_search doesn't work as expectedstd::binary_search 没有按预期工作
【发布时间】:2017-04-03 17:32:44
【问题描述】:

我尝试使用std::binary_search制作一个检查数字是否在向量中的程序

我知道我可以使用std::find,但我听说std::binary_searchstd::find 快​​很多,所以如果我需要检查一个数字是否在容器中,我想学习使用它.

代码:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::cout << "Enter number of elements: ";
    int n;
    std::cin >> n;
    std::vector<int> v(n);

    std::cout << "Enter the elements: ";
    std::for_each(v.begin(), v.end(), [](int &x)
    {
        std::cin >> x;
    });

    std::cout << "Enter a number: ";
    int number;
    std::cin >> number;

    bool doesItExist = std::binary_search(v.begin(), v.end(), number);

    if(doesItExist == false)
    {
        std::cout << "It doesn't exist!";
    }
    else std::cout << "It exists!";

    return 0;
}

我认为如果在容器中找到数字,std::binary_search 应该返回 true

现在我将用几个例子来解释我的代码会发生什么

在以下所有示例中,我将使用 10 个元素:

Enter number of elements: 10
Enter the elements: 1 10 100 -11 -112 -17 44 -99 99 558

Enter a number: 1
It doesn't exist!

Enter a number: 10
It doesn't exist!

它将继续这样,直到我输入最后两个数字之一(99558

前最后一个数字:

Enter a number: 99
It exists!

最后一个数字:

Enter a number: 558
It exists!

我不知道为什么会这样。 如果有人能解释为什么会发生这种情况,为什么只有最后两个数字有效? 有什么办法可以解决这个问题?

谢谢

【问题讨论】:

    标签: algorithm vector binary-search


    【解决方案1】:

    您误解了binary search 的工作方式:您不能以任意顺序输入数字,并期望binary_search 找到匹配项;必须订购该范围内的物品。这就是二分搜索在决定从中间、右边或左边走哪条路时所做的假设。

    如果你在读取数据后将这一行添加到你的代码中,问题将得到解决:

    std::sort(v.begin(), v.end());
    

    此外,如果您按排序顺序输入数字,您的代码将无需修改即可工作:

    -112 -99 -17 -11 1 10 44 99 100 558
    

    【讨论】:

    • 谢谢!需要对数字进行排序以使binary_search 工作的原因是什么?
    • @ihatestrings 二进制搜索是您用来在字典中查找单词的方法。现在想象一下当字典没有排序时应用相同的方法。
    【解决方案2】:

    通常对已排序的向量或数组应用二分查找

    你的似乎没有排序。

    对向量进行排序,然后重新检查结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2020-03-18
      • 2012-06-14
      • 2014-11-15
      • 1970-01-01
      • 2012-07-02
      相关资源
      最近更新 更多