Boost logo

Boost Users :

Subject: Re: [Boost-users] [Iterators] How to implement proxy iterators?
From: Jeffrey Lee Hellrung, Jr. (jeffrey.hellrung_at_[hidden])
Date: 2012-02-24 13:27:38


On Fri, Feb 24, 2012 at 12:26 AM, Oswin Krause <
Oswin.Krause_at_[hidden]> wrote:

> Hi Everybody,
>
> I'm trying to implement a proxy_iterator for ublas::matrix which should
> behave as an iterator over the matrix rows.
>
> My "obvious" solution does not seem to work:
>
> typedef boost::numeric::ublas::matrix<double> Matrix;
> typedef boost::numeric::ublas::matrix_row<Matrix> MatrixRow;
> typedef boost::numeric::ublas::vector<double> Vector;
>
> struct MatrixIterator:
> public boost::iterator_facade<
> MatrixIterator,
> Vector,//the semantic value type is a Vector
> boost::random_access_traversal_tag,
> MatrixRow//reference is a row of a matrix
> >{
> //snip constructors
> private:
> friend class boost::iterator_core_access;
>
> //snip iterating stuff
>
> //fun part
> MatrixRow dereference() const {
> return row(*m_matrix,m_element);
> }
> std::size_t m_element;
> Matrix* m_matrix;
> };
>
> which reuslts in an error that MatrixRow can't be implicitely casted to
> Vector. Which is correct. At the moment I'm using a 90% hacked workaround
> which changes the ValueType of the Iterator to MatrixRow. This seems to
> work as long as I don't use algorithms which rely on the actual value_type
> of the iterator (for example iter_swap as implemented in the gnu libstdc++
> will fail miserably even though a correct swap is implemented for the
> MatrixRow...different story )
>
> Since I need std::random_shuffle I am out of luck. I tried to find the
> actual requirements of iterator_facade with respect to
> ValueType/ReferenceType in the documentation, but was not able to find
> them.
> Does someone now a solution to this problem which works and results in an
> iterator which can safely be used in random_shuffle? Or can point me to
> the correct requirements?
>

See, for example,

http://www.boost.org/doc/libs/1_48_0/libs/iterator/doc/ReadableIterator.html

which states that, for a ReadableIterator i, *i must have a type
convertible to the iterator's value_type. Further, for iterator_facade, the
type of *i is the iterator's reference type. Therefore, reference must be
convertible to value_type.

Proxy references are perfectly fine, you just have to ensure they
interoperate well with (i.e., are convertible to) the iterator's value_type.

HTH,

- Jeff



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net