c++中的binary_search意外行为
binary_search in c++ unexpected behaviour
下面的代码段将返回我0。我原以为是1。这里怎么了?
#include <iostream>
#include <iterator>
#include <ostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
vector<int> v;
int arr[] = {10,20,30,40,50};
v.push_back(11);
v.push_back(22);
copy(arr,arr + sizeof(arr)/sizeof(arr[0]),back_inserter(v)); // back_inserter makes space starting from the end of vector v
for(auto i = v.begin(); i != v.end(); ++i){
cout << *i << endl;
}
cout << endl << "Binary Search - " << binary_search(v.begin(), v.end(), 10) <<endl; // returns bool
}
我使用的是gcc/usr/lib/gcc/i686-linux-gnu/4.6/lto-wrapper
我运行了程序,看到了这个:
11
22
10
20
30
40
50
Binary Search - 0
您的数组未排序,因此二进制搜索失败。(它看到11
在第一个位置,并得出10
在这里不存在的结论)
您可以确保在二进制搜索之前对数组进行排序,也可以使用常规的std::find
。
binary_search
表示:
检查排序范围
[first, last)
是否包含等于value
。第一个版本使用operator<
来比较元素第二版本使用给定的比较函数CCD_ 8。
您的列表未排序,它包含10
之前的元素11
和22
。
您的数组没有排序,所以binary_search
得到了未定义的行为。尝试std::find
而不是
bool found = std::find(v.begin(), v.end(), 10) != v.end()
&教派;C++11标准的25.4.3.4(3242草案)
- Requires:[first,last)的元素e相对于表达式e<value and!(value<e)或comp(e,值)和!comp(值,e)。同样对于[第一、最后]的所有元素e,e<值意味着!(value<e)或comp(e,value)暗示!comp(值,e)
"意外行为"?这里没有什么意外。
二进制搜索算法的整个思想是利用输入数组是排序的事实。如果数组没有排序,就不能对其进行任何二进制搜索。
当您使用std::binary_search
(以及所有其他基于二进制搜索的标准算法)时,输入序列必须根据与std::binary_search
使用的比较谓词相同的比较谓词进行排序。由于您没有向std::binary_search
传递任何自定义谓词,因此它将使用<
运算符定义的排序。这意味着您的输入整数序列必须按升序排序。
在您的情况下,输入序列不满足该要求。std::binary_search
不能在其上使用。
相关文章:
- 在C++中对T*类型执行std::move的意外行为
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 处理除以零会导致<csignal>意外行为
- vscode下的Arduino代码出现意外编译错误
- 使用++运算符会导致意外的结果
- 套接字读取后,我在缓冲区中看到意外输入
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 使用vscode调试时,GDB意外退出
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- 尝试将字符串/字符转换为整数会产生意外结果
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- C++标头错误 C2238 意外标记";"
- C++中意外的多头值
- vector.size() 在比较中意外工作
- 使用 malloc() 时出现意外大小
- 多线程程序中出现意外的内存泄漏
- QTableview Search
- LeetCode 1011.Binary Search,C++和Python的想法相同,但输出不同
- 为什么static_cast基础类型的枚举类int8_t获得意外值?
- 字符串比较中的意外输出