I was looking at how the upper_bound and lower_bound algorithms work in stl on these pages: lower_bound, upper_bound, and it's documented the same way on these pages: lower_bound, upper_bound
Looking at the code from the links, they seem to do exactly the same thing to me, with only the following lines being different (looking at the code from the first 2 links):
lower_bound (line 10):
if (*it<val) { // or: if (comp(*it,val)), for version (2)
upper_bound (line 10):
if (!(val<*it)) // or: if (!comp(val,*it)), for version (2)
but surely reversing the compared elements and then comparing them to false is a double negative, and thus they do exactly the same thing?
Is there actually a difference that I'm just not seeing, Is this an error in the documentation on the websites? If the latter, what would be the correct way?
upper_bound() is a standard library function in C++ defined in the header . It returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found.
Iterator upper_bound (Iterator first, Iterator last, const val) lower_bound returns an iterator pointing to the first element in the range [first,last) which has a value not less than 'val'. and if the value is not present in the vector then it returns the end iterator.
In mathematics, particularly in order theory, an upper bound or majorant of a subset S of some preordered set (K, ≤) is an element of K that is greater than or equal to every element of S. Dually, a lower bound or minorant of S is defined to be an element of K that is less than or equal to every element of S.
The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than val. This means that the function returns an iterator pointing to the next smallest number just greater than or equal to that number.
value a a a b b b c c c
index 0 1 2 3 4 5 6 7 8
bound l u
Where l
represents the lower bound of b
, and u
represents the upper bound of b
.
So if there are range of values that are "equal" with respect to the comparison being used, lower_bound
gives you the first of this, upper_bound
gives you one-past-the-end of these. This is the normal pattern of STL ranges [first, last)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With