使用std :: vector的奇怪事情

Pen*_*Sun 0 c++ vector

我写了一个简单的代码,将2,4,8,16,32,3,9,27,5,6,7插入到一个矢量对象中.插入这些数字后,我用std :: binary_search检查8,但奇怪的是它返回0.

这是代码.我不知道为什么.有人能帮助我吗?非常感谢!

#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;
}  
Run Code Online (Sandbox Code Playgroud)

Cor*_*bin 7

必须对序列进行排序std::binary_search.如果序列未排序,则行为未定义.

您可以先使用std::sort它进行排序,或者根据您需要的性能类型,您可以使用std::find它进行线性搜索.