Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between upper_bound and lower_bound in stl

Tags:

c++

stl

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?

like image 597
xEric_xD Avatar asked Jan 31 '17 13:01

xEric_xD


People also ask

What is Upper_bound in STL?

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.

What is Upper_bound and lower_bound in C++?

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.

What is the difference between lower bound and upper bound?

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.

What does lower_bound function do?

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.


1 Answers

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).

like image 161
BoBTFish Avatar answered Sep 18 '22 12:09

BoBTFish