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.
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
.
The Standard says :
Returns: The furthermost iterator
i
in the range[first, last]
such that for every iteratorj
in the range[first, i)
the following corresponding conditions hold:*j < value
orcomp(*j, value) != false
.
Now:
[first, last]
for an empty container has a single member, namely the iterator returned by its member function end()
. i
can therefore by only end()
. [first, i)
, which is [end, end())
. end()
and lower then end()
at the same time. Since there is no every iterator j
, I guess the quoted sentence can be rewritten into:
Returns: The furthermost iterator i
in the range [first, last]
.
Which implies that the only i
that can be returned is end()
.
std :: lower_bound回答了这个问题,“Where(就像在迭代器值之前)是第一个可以插入给定元素而不违反排序的地方?”如果给定的[ first,last ]范围为空,则只有在最后一个位置插入任何东西(等于第一个 ),所以这就是lower_bound返回的内容。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.