Cursor vs iterator pattern

I have seen in numerous texts that the term “cursor” is used interchangeably with the term “iterator”. However, it seems wrong that they are treated as one and the same.

For me, an iterator allows iteration of a container without knowing the container itself. On the other hand, the cursor also allows iteration of the container, but has implementation details specific to the type of container, so it retains a reference to the container. In addition, the cursor interface reflects a container type interface similar to a facade texture.

Here is an example of what I consider the 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 am making a distinction between iterators and cursors based on their dependency or knowledge of the container they use. Is this a suitable difference? If not, what would you think of the design pattern that I described in the above code example?

Please note that my code sample above should be considered as pseudo-code, since I did not compile it, and it also does not need the required constructors.

+4
source share
4 answers

The sample cursor you described is a combination of two patterns: a proxy and an iterator. The reason the standard library is different is to avoid unnecessarily combining these two types of behavior.

+6
source

Wikipedia redirects the cursor pattern to the iterator pattern page. With that in mind, I would say that you split your hair. If we can assume that Wikipedia is the ultimate link, these two terms can be used interchangeably.

+1
source

Iterators (at least as defined in the C ++ standard) do not give you access to the properties of the base container, but this information is available to you through different categories of iterators (which are available through iterator_tags ).

I also think your example is flawed. Why IsHardCover() data collection mirror the data interface (for example, IsHardCover() ) when I can access the contained value and request its properties myself?

0
source

Traditionally, long before the design template was used, cursors, where more powerful than iterators, since they allowed to change the basic data structure to a greater extent. Like insertBefore (), insertAfter () or insertAt (), etc. Some implementations allowed him to use several cursors in one container, and they informed each other about manipulations (they are called stable iterators today or stable data structures)

0
source

All Articles