C ++中的binary_search意外行为 [英] binary_search in c++ unexpected behaviour
本文介绍了C ++中的binary_search意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码段向我返回0.我希望它是1.这是怎么回事?
The following snippet is returning me 0. I expected it to be 1. What's wrong going on here?
#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
I am using gcc /usr/lib/gcc/i686-linux-gnu/4.6/lto-wrapper
推荐答案
我运行了程序并看到了:
I ran the program and saw this:
11
22
10
20
30
40
50
Binary Search - 0
您的数组未排序,因此二进制搜索失败.(它在第一个位置看到 11
,并得出结论 10
在这里不存在)
Your array is not sorted, therefore, binary search fails. (it sees 11
in the first position, and concludes 10
does not exist here)
您要么要确保在二进制搜索之前对数组进行排序,要么使用常规的 std :: find
.
You either want to ensure the array is sorted before binary searching or use the regular std::find
.
这篇关于C ++中的binary_search意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文