Topic: Random access iterators and operator[]


Author: Kresimir Fresl <fresl@grad.hr>
Date: 1997/03/07
Raw View
In section 24.1.5. `Random access iterators' in table 7 (`Random
access iterator requirements') it is said that the return type
of expression `a[n]' is `convertible to T'. This is very weak
requirement: it seems that (in general) we cannot assume that
`a[n]' is lvalue, that is, that we cannot write `a[n] = t'.

On the other hand, it is also said that operational semantics
of `a[n]' is `*(a + n)'. But in table 5, `Forward iterator
requirements' (sec. 21.1.3), return type of `*a' is defined
as `T&', and it is said: `If X is mutable, *a = t is valid'.
[BTW, in original HP STL documentation and in Musser & Saini's
book return type of `*a' is defined as `convertible to T',
but with the additional requirement `If X is mutable,
*a = t is valid'.]

Is this an oversight, or we really cannot assume that `a[n]'
is lvalue? (Or I misunderstood the term `convertible to T'.)

If we cannot assume this, isn't this too severe restriction?
For example, next definition of twodimensional array, that is,
of its operator[], is illegal:

  #include <vector.h>

  template <typename T>
  class array2d {
    public:
    typedef typename vector <T>::iterator        iterator;
    typedef typename vector <T>::const_iterator  const_iterator;
    typedef typename vector <T>::size_type       size_type;

    // ...
    array2d (size_type r, size_type c, T const& val = T())
    : elems (r*c, val), rows (r), nr (r), nc (c) {
      init_rows();
    }

    iterator operator[] (size_type i) { return rows[i]; }
    const_iterator operator[] (size_type i) const { return rows[i]; }

  protected:
    vector <T> elems;
    vector <iterator> rows;
    size_type nr;
    size_type nc;

    void init_rows() {
      rows[0] = elems.begin();
      for (size_type i = 1; i < nr; ++i)
        rows[i] = rows[i-1] + nc;
    }
  };

(This is C++ version of 2D arrays in `Numerical Recipes' by
Press et al.)

Idea is, of course, to provide `syntactic sugar' `a2d[i][j]'.

fres
---
[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]