[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
RE: iterators (WAS: computer-go: Languages for programming go are?)
> > > Many Faces is C, not C++, and I wouldn't create new iterators in my
inner
> > > loops, because it seems too slow. All of the loops in the example
would
> > > just be walking linked lists, so they are very simple and fast.
> >
> >The iterators are mostly syntactic sugar that gets inlined without loss
of
> >efficiency. The LibertyIterator essentially boils down to iteration
through
> >an array; the NeighborBlockIterator has to call a function to compute the
> >neighboring blocks first, eliminating duplicates. One advantage of using
> >iterator classes is that I can change the implementation (e.g. from list
to
> >array) without having to change any of the client code.
>
> So there is no call to new() in each for loop to allocate memory for the
> iterator object?
Right, no dynamic memory allocation. It just uses simple inline functions
that the compiler can optimize away. Here's the code for the array iterator
(minus some debugging code):
//==========================================================================
====
class ArrayIterator
//==========================================================================
====
{
public:
ArrayIterator(const UndoArray& array) : m_array(array), m_index(0) {}
void operator++() { m_index++; }
// Advance the state of the iteration to the next element.
int operator*() const { return m_array[m_index]; }
// Return the value of the current element.
operator const bool() const { return m_index < m_array.Count(); }
// Return true if iteration is valid, otherwise false. (Note that Count()
// is a simple accessor function.)
private:
const UndoArray& m_array;
int m_index;
ArrayIterator(const ArrayIterator&); // not implemented
ArrayIterator& operator=(const ArrayIterator&); // not implemented
};
The ListIterator class provides the same functions, also all inlined.
There's also another iterator for arrays of points that are null-terminated.
The NeighborBlockIterator is built on that one, as follows:
//==========================================================================
====
class NeighborBlockIterator : public PointIterator<PointType>
//==========================================================================
====
{
public:
NeighborBlockIterator(const GoBoard& board, Point p, BlackWhite c)
: PointIterator<PointType>(m_points)
{
board.NeighborBlocks(p, c, m_points);
}
NeighborBlockIterator(const GoBoard& board, Point p, BlackWhite c, int
maxLib)
: PointIterator<PointType>(m_points)
{
board.NeighborBlocks(p, c, maxLib, m_points);
}
private:
PointType m_points[5]; // At most 4 neighbor points, plus terminator.
};
> David Fotland
Anders Kierulf
www.smartgo.com