If I have the following vector {10 10 10 20 20 20 30 30} and I want the function to return the position of the integer = X or the directly smaller element after X, as, for example, if I search for 11, I want the function to return 2, since the second element (10) is the first smaller element than 11 in the vector.
I tried to use lower_bound, but this does not work.
int myints[] = {10,20,30,30,20,10,10,20}; vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20 vector<int>::iterator low,up; sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30 low=lower_bound (v.begin(), v.end(), 11); // up= upper_bound (v.begin(), v.end(), 11); // cout << "lower_bound at position " << int(low- v.begin()) << endl; cout << "upper_bound at position " << int(up - v.begin()) << endl; return 0;
this code outputs:
lower_bound at position 3 upper_bound at position 3
c ++ vector stl binary-search
Loers antario
source share