Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::adjacent_find(last, last) undefined?

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 it such that *it == *(it+1) for the first version or p(*it, *(it + 1)) != false for 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?

like image 572
Dev Null Avatar asked Oct 23 '25 20:10

Dev Null


1 Answers

No. It's well-defined.

Quoting C++ standard draft N4296, Section 25.2.8/1:

Returns: The first iterator i such that both i and i + 1 are in the range [first,last) for which the following corresponding conditions hold: *i == *(i + 1), pred(*i, *(i + 1)) != false. Returns last if 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, last is returned

like image 109
iBug Avatar answered Oct 25 '25 11:10

iBug