making my own iterator

J

John

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;
}

Thanks,
--j
 
N

Noah Roberts

John said:
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?

use boost's iterator library.
 
K

Kai-Uwe Bux

John said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top