1

次のスニペットでは 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 を使用しています

4

4 に答える 4

4

「予期しない動作」?ここには予想外のことは何もありません。

二分探索アルゴリズムの全体的な考え方は、入力配列がソートされているという事実を利用しています。配列がソートされていない場合、バイナリ検索は実行できません。

を使用する場合std::binary_search(および他のすべての標準的な二分探索ベースのアルゴリズムと同様)、 で使用されるものと同じ比較述語に従って、入力シーケンスを並べ替える必要がありますstd::binary_search。カスタム述語を に渡さなかったため、演算子std::binary_searchによって定義された順序が使用され<ます。つまり、整数の入力シーケンスは昇順でソートする必要があります。

あなたの場合、入力シーケンスはその要件を満たしていません。std::binary_searchその上では使用できません。

于 2013-07-11T21:21:55.303 に答える