How to find the first smaller element than the integer X in the vector? (C ++)

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 
+4
c ++ vector stl binary-search
source share
3 answers

cppreference tells me std::lower_bound

Returns an iterator pointing to the first element in the range [first, last], which is not less than the value

and std::upper_bound

Returns an iterator pointing to the first element in the range [first, last], which is greater than the value

In this case, given the vector containing 10 10 10 20 20 20 30 30 , I would expect both functions to point to the first 20 , which sits at position 3 in the vector and is really the result that you got both times. If you asked for 20 , std::lower_bound would return an iterator, pointing to the first 20 in the vector (position 3) ... the first number is at least 20 and the same result you get when asking 11 . In this case, however, std::upper_bound will return an iterator pointing to the first 30 (position 6), which is the first value greater than 20.

Just move the iterator back to get the last value less than the target number, std::prev is one way to do this.

+8
source share

At the top, the top returns the first element that is larger than the test element, so the one that was before (if it exists) will be the one you need?

+1
source share

you could do it ... it might be better to return an iterator if the vector is empty ...

 auto find_next_smaller(vector<int> vec, const int x) { std::sort(vec.begin(), vec.end()); auto it = std::lower_bound(vec.begin(), vec.end(), x); if (it == vec.end()) { it = (vec.rbegin()+1).base(); } else if (it != vec.begin() && *it > x) { --it; } return it; } 
0
source share

All Articles