Wrapping linked lists in iterators

后端 未结 5 726
青春惊慌失措
青春惊慌失措 2021-01-20 01:21

A set of APIs that I commonly use follow a linked-list pattern:

struct SomeObject
{
    const char* some_value;
    const char* some_other_value;
    SomeObj         


        
5条回答
  •  日久生厌
    2021-01-20 01:42

    First, of course, for real use, you almost certainly shouldn't be writing your own linked list or iterator at all. Second, good uses for linked lists (even one that's already written, debugged, etc.) are also pretty rare -- except in a few rather unusual circumstances, you should probably use something else (most often vector).

    That said, an iterator is typically a friend (or nested class) of the class to which it provides access. It provides the rest of the world with an abstract interface, but the iterator itself has direct knowledge of (and access to) the internals of the linked list (or whatever container) to which it provides access). Here's a general notion:

    // warning: This is really pseudo code -- it hasn't been tested, and would 
    // undoubtedly require a complete rewrite to even compile, not to mention work.
    template 
    class linked_list { 
    
    public:
        class iterator;
    
    private:
        // A linked list is composed of nodes.
        // Each node has a value and a pointer to the next node:    
        class node { 
            T value;
            node *next;
            friend class iterator;
            friend class linked_list;
        public:
            node(T v, node *n=NULL) : value(v), next(n) {}
        };
    
    public:
    
        // An iterator gives access to the linked list.
        // Operations: 
        //      increment: advance to next item in list
        //      dereference: access value at current position in list
        //      compare: see if one iterator equals another    
        class iterator { 
            node *pos;
        public:
            iterator(node *p=NULL) : pos(p) {}
            iterator operator++() { 
                assert(pos); 
                pos = pos->next; 
                return *this;
            }
            T operator*() { return pos->value; }
            bool operator!=(iterator other) { return pos != other.pos; }
        };
    
        iterator begin() { return iterator(head); }
        iterator end()   { return iterator(); }
    
        void push_front(T value) { 
            node *temp = new node(value, head); 
            head = temp;
        }
    
        linked_list() : head(NULL) {}
    
    private:
        node *head;
    };
    

    To work along with the algorithms in the standard library, you have to define quite a bit more than this tried to (e.g., typedefs like value_type and reference_type). This is only intended to show the general structure.

提交回复
热议问题