因为这里值得的是我最终实现的算法。代码不完整,但可能对其他人有用:
//forward declarations
template <typename T> class Grid;
template <typename T> class rectIterator;
//friend forward declarations
template<class T>
bool operator!=(rectIterator<T> const& left, rectIterator<T> const& right);
template<class T>
class rectIterator: public std::iterator<std::forward_iterator_tag, GridTile<T> >{
public:
typedef GridTile<T> const& const_reference;
typedef GridTile<T>& reference;
typedef GridTile<T> const* const_pointer;
typedef GridTile<T>* pointer;
private:
Grid<T>* mpGrid;
int mRow;
int mCol;
int mMinRow;
int mMinCol;
int mMaxRow;
int mMaxCol;
public:
rectIterator(Grid<T>& grid,Rectangle const& rect):
mpGrid(&grid){
mpGrid->getRowCol(mpGrid->getTileId(rect.bottomLeft()),mMinRow,mMinCol);
mpGrid->getRowCol(mpGrid->getTileId(rect.topRight()),mMaxRow,mMaxCol);
mRow = mMinRow;
mCol = mMinCol;
}
rectIterator():
mpGrid(0){
mMinRow= -1;
mMinCol=-1;
mMaxRow =-1;
mMaxCol =-1;
mCol = 0;
mRow = 0;
}
rectIterator<T>& operator++(){
if(mCol<=mMaxCol){
++mCol;
}else if(mRow<=mMaxRow){
++mRow;
mCol = mMinCol;
}else{
mCol = mpGrid->getCols();
mRow = mpGrid->getRows();
mpGrid=0;
}
return *this;
}
reference operator*() const throw(std::out_of_range, std::runtime_error){
return mpGrid->at(mRow,mCol);
}
pointer operator->() const throw(std::out_of_range, std::runtime_error){
return &(mpGrid->at(mRow,mCol));
}
int row()const{
return mRow;
}
int col()const{
return mCol;
}
friend bool operator!=<>(rectIterator<T> const& left, rectIterator<T> const& right);
};
template<class T>
bool operator!= (rectIterator<T> const& left, rectIterator<T> const& right){
return (left.mpGrid != right.mpGrid);
//DIRTY this is no full compare but fast and sufficient at the moment
}