【发布时间】:2017-04-03 17:32:44
【问题描述】:
我尝试使用std::binary_search制作一个检查数字是否在向量中的程序
我知道我可以使用std::find,但我听说std::binary_search 比std::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
1°
Enter a number: 1
It doesn't exist!
2°
Enter a number: 10
It doesn't exist!
它将继续这样,直到我输入最后两个数字之一(99 或 558)
前最后一个数字:
Enter a number: 99
It exists!
最后一个数字:
Enter a number: 558
It exists!
我不知道为什么会这样。 如果有人能解释为什么会发生这种情况,为什么只有最后两个数字有效? 有什么办法可以解决这个问题?
谢谢
【问题讨论】:
标签: algorithm vector binary-search