By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,131 Members | 1,386 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,131 IT Pros & Developers. It's quick & easy.

Dereferencing past-the-end iterators

P: n/a
Hello,

I was wondering, does dereferencing past-the-end
iterators yield undefined behavior? Especially, is
the result of calling an STL algorithm on an empty
range undefined?

For example (pseudocode):

begin = find(...);
end = find(...);

sort(begin, find, pred);

If begin is a past-the-end iterator, is the call
to sort() an unsafe operation? Is it good practice
to check iterators for being valid before passing
them to an STL algo?

Regards,
Matthias
Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

Jul 23 '05 #2

P: n/a
Thomas Tutone wrote:
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.


Alright, that's what I was worried about. Thanks Tom.
Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.