Question

I'm writing a special iterator class that works like std::istream_iterator and many others by using a default-constructed instance to mark end of iteration. I want to give it the bidirectional iterator category. After running the following code:

MyIterType i_cur(get_some_iter()), i_end;
while(i_cur != i_end) ++i_cur;

do the standard requirements for bidirectional iterators impose the following to be valid?

  1. --i_cur
  2. ++i_cur
  3. --i_end or ++i_end

Thank you for quoting the standard if possible. I compile in C++03, but if C++11 introduces changes, I'm also interested to know them.

Was it helpful?

Solution

The Standard says that the answer to your question is yes:

[C++03] : 24.1.4 Bidirectional iterators

Table 75—Bidirectional iterator requirements (in addition to forward iterator)

   expression    return type    operational    assertion/note
                                semantics    pre/post-coindition
   ========      ============   ============ ====================
   --r             X&                         pre: there exists s such
                                              that r == ++s.
                                              post: s is dereferenceable.
                                              --(++r) == r.
                                              --r == --s implies r
                                              == s.
                                              &r == &--r

OTHER TIPS

In 24.2.6 in C++11, Table 110 gives the additional requirements for a bidirectional iterator.

In particular, if there exists s such that r == ++s, then --r must be valid and the resulting r must be dereferenceable. In addition:

  • --(++r) == r.
  • --r == --s implies r == s.
  • &r == &--r.

So unless the initial i_cur returned by get_some_iter is a past-the-end iterator, the final i_cur has a predecessor and so must be decrementable. The same holds for i_end, since it is the successor of the predecessor of the final i_cur.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top