下面的片段给我回复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
}
Run Code Online (Sandbox Code Playgroud)
我正在使用gcc /usr/lib/gcc/i686-linux-gnu/4.6/lto-wrapper
mil*_*bug 12
我运行程序看到了这个:
11
22
10
20
30
40
50
Binary Search - 0
Run Code Online (Sandbox Code Playgroud)
您的数组未排序,因此二进制搜索失败.(它11
在第一个位置看到,并且10
此处不存在结论)
您要么确保在二进制搜索之前对数组进行排序,要么使用常规数组std::find
.