* Please refer to this document for reference from blog.csdn.net/wtz1985
In the previous article, I have already introduced why container implementation and how to implement container. This chapter will introduce how to separate algorithms from containers and in containers, the basic interface definition is implemented, but the container does not implement specific operations, such as moving to a node or comparing the values of two nodes. Separating these algorithms from containers is the so-called iterator ). The following is the implementation of some code interfaces:
1. interface definition.
- /* -------- Iterator. h --------*/
- # Ifndef _ iterator_h
- # DEFINE _ iterator_h
- Struct _ iterator;
- Typedef struct _ iterator;
- Typedef void (* iteratornextfunc) (iterator * thiz );
- Typedef void (* iteratorprevfunc) (iterator * thiz );
- Typedef void (* iteratoradvancefunc) (iterator * thiz, size_t off_set );
- Typedef void (* iteratorbeginfunc) (iterator * thiz );
- Typedef void (* iteratorendfunc) (iterator * thiz );
- Typedef int (* iteratorcomparefunc) (iterator * X, iterator * y );
- Typedef void (* iteratorsetfunc) (iterator * thiz, void * data );
- Typedef void * (* iteratorgetfunc) (iterator * thiz );
- Typedef void (* iteratordestroyfunc) (iterator * thiz );
- Struct _ iterator
- {
- Iteratornextfunc next;
- Iteratorprevfunc Prev;
- Iteratoradvancefunc advance;
- Iteratorbeginfunc begin;
- Iteratorendfunc end;
- Iteratorcomparefunc compare;
- Iteratorsetfunc set;
- Iteratorgetfunc get;
- Iteratordestroyfunc destroy;
- };
- Static inline void iterator_next (iterator * thiz)
- {
- Assert (thiz! = NULL & thiz-> next! = NULL );
- Thiz-> next (thiz );
- Return;
- }
- Static inline void iterator_prev (iterator * thiz)
- {
- Assert (thiz! = NULL & thiz-> Prev! = NULL );
- Thiz-> Prev (thiz );
- Return;
- }
- Static inline void iterator_advance (iterator * thiz, size_t off_set)
- {
- Assert (thiz! = NULL & thiz-> advance! = NULL );
- Thiz-> advance (thiz, off_set );
- Return;
- }
- .......
- # Endif
2. Different interface implementations:
Linked List:
- /* -------- Iterator_list.h ---------*/
- # Ifndef _ iterator_list_h
- # DEFINE _ iterator_list_h
- # Include "iterator. H"
- Iterator * iterator_list_create (Dlist * thiz );
- # Endif
Dynamic Array mode:
- /* -------- Iterator_vector.h ---------*/
- # Ifndef _ iterator_vector_h
- # DEFINE _ iterator_vector_h
- # Include "iterator. H"
- Iterator * iterator_vector_create (vector * thiz );
- # Endif
The above is the implementation of the iterator interface, and the specific operation is not implemented here. With the container and iterator intermediate interfaces, You can freely choose the appropriate structure to implement your own functions. I hope you can give me more advice on some bad things.
~~ End ~~