std::adjacent_find
searches the range [
first,last) for two consecutive identical elements.Return value
an iterator to the first of the first pair of identical elements, that is, the first iterator
itsuch that*it == *(it+1)for the first version orp(*it, *(it + 1)) != falsefor the second version.If no such elements are found, last is returned
However, it is not clear how it is supposed to handle the range {last, last}.
Both possible implementations on cppreference have the following check:
if (first == last) {
return last;
}
Is std::adjacent_find(last, last) UB or the standard does define it?
No. It's well-defined.
Quoting C++ standard draft N4296, Section 25.2.8/1:
Returns: The first iterator
isuch that bothiandi + 1are in the range[first,last)for which the following corresponding conditions hold:*i == *(i + 1),pred(*i, *(i + 1)) != false. Returnslastif no such iterator is found.
So, if first == last, it means the search range is empty, and thus the method should return last.
The check on CppReference is very correct. It is also mentioned on CppReference that:
If no such elements are found,
lastis returned
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With