"PolkaHead" <sc***********@gmail.comwrote:

I was wondering if there's a way to traverse a two-dimensional vector

(vector of vectors) with a nested for_each call.

The code included traverses the "outer" vector with a for_each, than it

relies on the PrintFunctor to traverse the "inner" vector with another

for_each. Is it possible to nest the second for_each, so I don't have

to include a for_each in my function object.

If you used an Array2D class instead of nested vectors, it would be

quite simple.

template < typename T, typename rep_type = typename std::deque< T

class Matrix

{

public:

typedef typename rep_type::size_type size_type;

typedef typename rep_type::reference reference;

typedef typename rep_type::const_reference const_reference;

typedef typename rep_type::iterator iterator;

typedef typename rep_type::const_iterator const_iterator;

Matrix(): _width( 0 ), _height( 0 ) { }

Matrix( size_type w, size_type h ):

_width( w ), _height( h ), _rep( w * h ) { }

size_type width() const { return _width; }

size_type height() const { return _height; }

reference at( size_type x, size_type y ) {

if ( x >= _width || y >= _height )

throw std::out_of_range( "Matrix::at(size_type, size_type)" );

return _rep[ x * _width + y ];

}

const_reference at( size_type x, size_type y ) const {

if ( x >= _width || y >= _height )

throw std::out_of_range( "Matrix::at(size_type, size_type)" );

return _rep[ x * _width + y ];

}

iterator begin() { return _rep.begin(); }

const_iterator begin() const { return _rep.begin(); }

iterator end() { return _rep.end(); }

const_iterator end() const { return _rep.end(); }

void swap( Matrix& m ) {

std::swap( _width, m._width );

std::swap( _height, m._height );

_rep.swap( m._rep );

}

private:

typename rep_type::size_type _width, _height;

rep_type _rep;

};

Matrix<ElementmyMatrix( 2, 3 );

// load

for_each( myMatrix.begin(), myMatrix.end(),

std::mem_fun( &Element::printName ) );

--

To send me email, put "sheltie" in the subject.