Matthias Kaeppler wrote:
I was wondering, does dereferencing past-the-end
iterators yield undefined behavior?
Yes.
Especially, is
the result of calling an STL algorithm on an empty
range undefined?
No, that's well defined. It doesn't do anything. In particular,
nothing gets dereferenced, so there's no undefined behavior.
For example (pseudocode):
begin = find(...);
end = find(...);
sort(begin, find, pred);
If begin is a past-the-end iterator
By "past-the-end iterator," I assume you in fact mean an iterator equal
to end(). Given that it's name is "end()," it's confusing for you to
refer to it as "past-the-end."
, is the call
to sort() an unsafe operation?
No, it's safe, because nothing gets dereferenced if begin==end.
Is it good practice
to check iterators for being valid before passing
them to an STL algo?
What do you mean by "valid"? An iterator equal to end() is valid, but
you can't dereference it. And end() is frequently the second iterator
passed to an algorithm. E.g.:
std::sort(seq.begin(), seq.end());
If seq is empty, then begin()==end(), there's nothing to sort, and
nothing gets dereferenced by the call to sort(). You don't have to
check for that.
Best regards,
Tom