John wrote:
>
I have a class of my own which has a 2d matrix of type T. I want to
give the users of my library an iterator to iterator thru all the
elements of this matrix ( they dont need to know anything about the
internal matrix). What is the easiest way to do this?
template< typename T >
class X{
// X::iterator needs to be defined for parsing data.
// const_iterator?
private:
vector< vector< T data;
}
The most easy to maintain is probably an iterator that does not really care
too much about the internal representation. You could do that as follows
[untested code]:
template < typename T >
class Matrix {
// the usual typedefs
typedef T value_type;
class iterator {
Matrix & the_matrix;
Matrix::size_type the_row;
Matrix::size_type the_col;
public:
Matrix::reference operator* ( void ) {
return ( the_matrix( the_row, the_col ) );
}
iterator operator++ ( void ) {
++ the_col;
if ( the_col == the_matrix.col_size() ) {
++ the_row;
the_col = 0;
}
return ( *this );
}
...
};
};
Note that in operator++ and its relatives, you have a choice for how to
traverse the matrix.
Also note that this iterator only relies on the interface of the Matrix
class. If you want to optimize for performance, you would need to tailor
the iterator towards the internal representation.
Best
Kai-Uwe Bux