Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::set::lower_bound(x) (effectively) defined as the smallest number >= x rather than the largest number <= x?

Tags:

c++

set

stl

Perhaps I'm misunderstanding the technical definition of lower bound but I would expect if I had a set a = { 0, 3, 4 } and computed the a.lower_bound(2) that the result would be 0. I.e. I would expect std::set::lower_bound to be close to the mathematical concept of infimum

And yet the standard library defines it as the largest number not less than (effectively >=) x.

What is the reasoning behind this?

like image 822
Catskul Avatar asked Jun 27 '12 15:06

Catskul


People also ask

What is the complexity of lower_bound?

Time Complexity of set::lower_bound() is O(logn), where n is the size of the set.

What will the lower_bound () function return if the element you passed as an argument isn't present in the vector VECT?

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 does lower_bound return in C++ if element is not present?

lower_bound in c++ stl returns an iterator even when the element is not present.

What does Lowerbound return if all elements are smaller?

lower_bound() returns an iterator to begin of the range. If all elements are lower than the searching element: lower_bound() returns an iterator to end of the range( No lower bound exists).


1 Answers

The "[lower|upper]_bound" functions are meant to return a place in a set where you could insert a key that would not violate the ordering of the set. Because an iterator of an STL set points to before the next element, if lower_bound(2) returned an iterator to 0, then inserting 2 would violate the order of your set, it would now be {2, 0, 3, 4}. Upper bound serves to show the last place you could insert without violating set order.

This is most useful if your set may have duplicate key entries. Consider {0, 3, 3, 4}. lower_bound(3) would return an iterator to here: {0, *, 3, 3, 4}, while upper_bound(3) would return it here: {0, 3, 3, *, 4}.

like image 77
Tawnos Avatar answered Nov 15 '22 19:11

Tawnos