Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL: Passing an empty container to lower_bound

Is the behavior for passing an empty container to std::lower_bound defined?

I checked cppreference.com and an old version of the C++ standard that I found online, but couldn't find a definite answer.

The cppreference.com documentation for std::deque::erase has a sentence

The iterator first does not need to be dereferenceable if first==last: erasing an empty range is a no-op.

I miss something like this for std::lower_bound and other algorithms.

like image 702
FelEnd Avatar asked Oct 11 '18 10:10

FelEnd


People also ask

What is lower_bound in STL?

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.

What does lower_bound return if not found?

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

Can we use lower_bound for set in C++?

The set::lower_bound() is a built-in function in C++ STL which returns an iterator pointing to the element in the container which is equivalent to k passed in the parameter.

Does lower_bound work on unsorted array?

Does lower_bound and upper_bound work with unsorted arrays also? Yes this will work only for sorted arrays.


1 Answers

Cppreference on the return value of std::lower_bound(first, last):

"[it returns] Iterator pointing to the first element that is not less than value, or last if no such element is found.".

(emphasis mine)

In an empty range, there will be no elements that satisfy the criteria, so last will be returned.

Concluding from this, applying std::lower_bound (and similar) on the empty range is well-defined. It does nothing and returns last, which is equal to first.

like image 92
Fureeish Avatar answered Sep 21 '22 17:09

Fureeish