In numerous texts, I’ve seen the term cursor used interchangeably with the term iterator. However, it doesn’t seem right that they are treated as the same thing.
To me, an iterator allows iteration of a container with no knowledge of the container itself. A cursor, on the other hand, allows iteration of a container as well but has implementation details specific to the container type, so it does keep a reference to the container. Additionally a cursor’s interface mirrors the interface of the container kind of like the facade pattern.
Here is an example of what I would consider a cursor:
class Book {};
class Library
{
std::vector<Book> books;
bool IsBookHardCover( int bookIndex );
bool IsBookSoftCover( int bookIndex );
BookCursor GetFirstBook();
};
class BookCursor
{
std::vector<Book>& books;
int currentBook;
bool IsHardCover();
bool IsSoftCover();
void Next();
};
So basically I make the distinction between iterators and cursors based on their dependency or knowledge of the container they iterate. Is this an appropriate distinction? If not, what would you consider the design pattern I’ve outlined in my code example above?
Note that my code example above should be treated as pseudocode since I did not compile it and it also lacks the constructors required.
The Cursor pattern you described is the combination of two patterns: Proxy and Iterator. The reason the standard library is different is to avoid needlessly coupling those two behaviors.