c++中的binary_search意外行为

binary_search in c++ unexpected behaviour

本文关键字:意外 search 中的 binary c++      更新时间:2023-10-16

下面的代码段将返回我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之前的元素1122

您的数组没有排序,所以binary_search得到了未定义的行为。尝试std::find而不是

bool found = std::find(v.begin(), v.end(), 10) != v.end()

&教派;C++11标准的25.4.3.4(3242草案)

  1. 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不能在其上使用。