Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Incrementing past end iterator

27 views
Skip to first unread message

Paul

unread,
Jan 11, 2016, 9:38:37 AM1/11/16
to
Suppose C is a random access container. I seem to remember reading that adding positive integers to iterators works fine so long as we don't travel more than 1 unit past the off-the-end iterator.

For example, if vec is a vector, auto z = vec.end() + 1; is fine (of course we can't dereference z, though).

However, auto z = vec.end() + 2; has undefined behaviour. Is this correct? I can't see a reference anywhere.

Thanks.

Paul

Alf P. Steinbach

unread,
Jan 11, 2016, 10:43:06 AM1/11/16
to
The end() iterator is already one past the end of the sequence. It's an
"after" the sequence iterator. I think that's what you probably read.


Cheers & hth.,

- Alf

Öö Tiib

unread,
Jan 11, 2016, 11:10:00 AM1/11/16
to
On Monday, 11 January 2016 16:38:37 UTC+2, Paul wrote:
> Suppose C is a random access container. I seem to remember reading that
> adding positive integers to iterators works fine so long as we don't travel
> more than 1 unit past the off-the-end iterator.
>

It was incorrect or you misread it or you misremember it. Traveling one unit
further than the "one past end" iterator is undefined behavior.

> For example, if vec is a vector, auto z = vec.end() + 1; is fine (of course
> we can't dereference z, though).

No. Dereferencing or incrementing past 'vec.end()' is undefined behavior.

>
> However, auto z = vec.end() + 2; has undefined behaviour. Is this correct?
> I can't see a reference anywhere.

That has also undefined behavior and so has 'vec.end() + 3'. 'vec.end()' *is*
one past end iterator already.
0 new messages