2013-07-18 103 views
0

我寫了一個簡單的代碼插入到矢量對象2,4,8,16,32,3,9,27,5,6,7。 插入這些數字後,我檢查與std :: binary_search爲8,但奇怪的是它返回0.奇怪的東西使用std :: vector

這是代碼。我不知道爲什麼。有人能幫助我嗎? 非常感謝!

#include <iostream> 
#include <math.h> 
#include <vector> 
#include <algorithm> 

using namespace std; 

void printVector(vector<int>const & p) { 
    for (int i = 0; i < p.size(); i++) 
     cout << p[i] << ' '; 
    cout << endl; 
}  

int main() { 
    const int max = 100; 
    int num; 
    vector<int> base; 

    for (int i = 2; i <= 7; i++) { 
     int expo = log(max)/log(i); 
     num = 1; 
     for (int iexp = 1; iexp < expo; iexp++) { 
      num *= i; 
      if (!binary_search(base.begin(), base.end(), num)) { // If the number is not in the vector 
       base.push_back(num); // Insert the number 
       printVector(base);  // Reprint the vector 
       cout << endl; 
      }  
     }  
    }  
    cout << binary_search(base.begin(), base.end(), 8) << endl; 
    printVector(base); 

    return 0; 
} 

回答

7

該序列必須按std::binary_search排序。如果序列未被排序,則行爲未定義。

您可以先使用std::sort對其進行排序,或者根據您需要的性能類型,可以使用std::find進行線性搜索。

4

二進制搜索要求向量進行排序。如果以隨機順序插入值,二進制搜索的結果將不可預知。

3

std::binary_search只適用於排序的序列。您需要先排序向量。