2013-07-18 129 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只适用于排序的序列。您需要先排序向量。