在{8,4,6,2}中搜索4时,std::binary_search是否有任何实现将返回true

Is there any implementation of std::binary_search will return true while search for 4 in {8, 4, 6, 2}?

本文关键字:是否 search binary 实现 true 返回 任何 std 4时 搜索      更新时间:2023-10-16

我在一本教科书中读到下面的一个问题,上面说1是一个可能的输出。我在VS和g++中尝试过,结果都是0。课本错了吗?

int t[] = { 8, 4, 6, 2 };
deque<int> d1(t, t + 4);
cout << binary_search(d1.begin(), d1.end(), 4) << endl;

课本是对的;这个问题是一个理论问题,即使尝试多个实现也不能帮助你伪造声明(你最多能做的就是找到一个证明声明的实现)。

binary_search需要一个排序的数组,如果你传递了一个未排序的数组——你就进入了未定义的行为领域,在那里一切都可能发生,包括找到你的数字并返回true

例如,一个碰巧使用数组中的第二个位置作为第一猜测的实现,或者切换到线性搜索短容器的实现,可能很容易做到这一点。见鬼,即使是这样的东西也是一个完全一致的实现:

template<class ForwardIt, class T>
bool binary_search(ForwardIt first, ForwardIt last, const T& value) {
// check the first two values just because
for(int i=0; i<2 && first != last; ++i, ++first) {
if(!(*first<value) && !(value<*first)) return true;
} 
first = std::lower_bound(first, last, value);
return (!(first == last) && !(value < *first));
}

也就是说,更有趣的是,不仅1是可能的输出,而且5或42也是可能的,尽管IMO的可能性小于"分段故障(堆芯转储)";也就是说:未定义的行为实际上是未定义的(我已经看到很多次libstdc++std::sort如果传递了一个没有定义严格弱排序的比较运算符,就会导致程序崩溃)。