Dereferencing past-the-end iterators

M

Matthias Kaeppler

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
 
T

Thomas Tutone

Matthias said:
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
 
M

Matthias Kaeppler

Thomas said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top