C++ 使用std::vector的奇怪事情
我编写了一个简单的代码,将2,4,8,16,32,3,9,27,5,6,7插入向量对象。 在插入这些数字后,我用std::binary_search检查8,但奇怪的是它返回0 这是代码。我不知道为什么。有人能帮我吗? 非常感谢C++ 使用std::vector的奇怪事情,c++,vector,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 printVe
#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
void printVector(矢量常数和p){
对于(int i=0;i cout二进制搜索要求对向量进行排序。如果以随机顺序插入值,则二进制搜索的结果将不可预测。必须为std::Binary\u search
对序列进行排序。如果序列未排序,则行为未定义
您可以使用std::sort
首先对其进行排序,或者,根据您需要的性能类型,您可以使用std::find
进行线性搜索。std::binary\u search
仅对排序序列有效。您需要首先对向量进行排序