问题
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?
回答1:
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)
.
回答2:
lower_bound
:
Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.
upper_bound
:
Returns an iterator pointing to the first element in the range [first,last) which compares greater than val.
Now there is a difference between being no less than something and greater than something.
For example, if you compare 4
and 5
, you can say that
5 is _not less than_ 4
5 is _greater than_ 4
However if you compare you compare 4
and 4
:
4 is _not less than_ 4
4 is _not greater than_ 4
回答3:
A simple answer is and less confusing WAY to remember this is below
std::lower_bound
- returns iterator to first element in the given range which is EQUAL_TO or Greater than
val.
std::upper_bound
- returns iterator to first element in the given range which is Greater than val
.
来源:https://stackoverflow.com/questions/41958581/difference-between-upper-bound-and-lower-bound-in-stl