Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ bidirectional iterator prefix increment

Observation 1: A C++ output iterator requires that &r == &++r, while an input iterator does not mention this requirement. See [C++11: 24.2.{3,4}]

Observation 2: Forward, bidirectional, and random-access iterators satisfy the input iterator requirements [24.2.{5,6,7}:1], but not necessarily the output iterator requirements unless they are mutable [24.2.1:4].

Observation 3: Bidirectional iterators add a prefix decrement operation, with the requirement &r == &--r [24.2.6].

So, is it true that a constant bidirectional iterator must satisfy &r == &--r but not necessarily &r == &++r, while a mutable bidirectional iterator must satisfy both?

Can you address how this requirement might influence an implementation?


MvG, below, asks the question I really meant:

  • When does it make sense for a constant Forward iterator to not satisfy &r == &++r?
like image 498
nknight Avatar asked Feb 25 '26 23:02

nknight


1 Answers

This is an indirect way of formulating the requirements, without explicitly specify a particular implementation. In particular &r == &++r is a way of saying that ++r cannot return a proxy object. The result must be the same iterator.

Here mutable isn't exactly the opposite of const in the usual way, but means writable and again refers to the requirements for an output iterator.

A bidirectional iterator must of course support both ++p and --p (by definition), but doesn't have to be writable/mutable.

The categories aren't exactly orthogonal between read/write and forward/backward movable, so the individual requirements are not a independent as they could have been. This causes some confusion.

I'm not sure if your conclusion follows from the observations, but don't think it would be an important freedom for an implementation. The fact that you have to support things like *++p and *p++ sets most of the limitations.

like image 167
Bo Persson Avatar answered Feb 27 '26 12:02

Bo Persson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!