在{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}?
我在一本教科书中读到下面的一个问题,上面说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
如果传递了一个没有定义严格弱排序的比较运算符,就会导致程序崩溃)。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 如何找到大小'x'数组是否完全填充,在C++?
- 检查值是否在集合p1和p2中,但不在p3中
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- C/C++预处理器是否可以检测一些编译器选项
- 是否存在std::search对应的函数,就像std::count对应std::find一样