c++ - weird things using std::vector -
this question has answer here:
i wrote simple code insert 2,4,8,16,32,3,9,27,5,6,7 vector object. after insert these numbers, check std::binary_search 8, weirdly returns 0.
here code. not know why. me? lot!
#include <iostream> #include <math.h> #include <vector> #include <algorithm> using namespace std; void printvector(vector<int>const & p) { (int = 0; < p.size(); i++) cout << p[i] << ' '; cout << endl; } int main() { const int max = 100; int num; vector<int> base; (int = 2; <= 7; i++) { int expo = log(max) / log(i); num = 1; (int iexp = 1; iexp < expo; iexp++) { num *= i; if (!binary_search(base.begin(), base.end(), num)) { // if number not in vector base.push_back(num); // insert number printvector(base); // reprint vector cout << endl; } } } cout << binary_search(base.begin(), base.end(), 8) << endl; printvector(base); return 0; }
the sequence must sorted std::binary_search
. behavior undefined if sequence not sorted.
you can use std::sort
sort first, or, depending on kind of performance need, can use std::find
linear search.
Comments
Post a Comment