Unlike lower_bound, upper_bound does not return an iterator to the element if it compares equivalent to value, but only if it compares strictly greater.
Is there an alternative if I want an upper_bound algorithm that is greater than or equal to.
Unlike lower_bound, upper_bound does not return an iterator to the element if it compares equivalent to value, but only if it compares strictly greater.
Is there an alternative if I want an upper_bound algorithm that is greater than or equal to.
You could decrease the iterator by 1.
auto begin = ...;
auto end = ...;
auto it = std::upper_bound(begin, end, target);
if (it == begin)
return it;
-- it;
if (*it < target)
return ++it;
else
return it;
The position of the iterator will be like this, assume you are searching for 2:
1 1 1 2 2 2 2 3 3 3 3
^ ^ ^
lb | ub
this function
1 1 1 1 3 3 3 3
^
lb & ub & this function
Despite the confusing name, std::lower_bound
actually does exactly what you want.
Returns an iterator pointing to the first element in the range [first, last) that does not satisfy element < value (or comp(element, value)), (i.e. greater or equal to), or last if no such element is found. https://en.cppreference.com/w/cpp/algorithm/lower_bound
std::set<int> s {0, 1, 3};
std::cout << s.lower_bound(2); // yields 3
std::cout << s.lower_bound(1); // yields 1
I did this using option (2)
https://en.cppreference.com/w/cpp/algorithm/upper_bound?force_isolation=true
Assuming you know your data type (int in this case, but you could easily template this):
std::upper_bound(v.begin(), v.end(), target,
[](const int &a, const int &b) { return a <= b; });