2013-05-01 74 views
0

的位置我有以下List类:检查哪个对象的迭代器是在

typedef int Elem;    // list base element type 
    class NodeList {    // node-based list 
    private: 
    struct Node {    // a node of the list 
     Elem elem;    // element value 
     Node* prev;    // previous in list 
     Node* next;    // next in list 
    }; 
    public: 
    class Iterator {    // an iterator for the list 
    public: 
     Elem& operator*();   // reference to the element 
     bool operator==(const Iterator& p) const; // compare positions 
     bool operator!=(const Iterator& p) const; 
     Iterator& operator++();   // move to next position 
     Iterator& operator--();   // move to previous position 
     friend class NodeList;   // give NodeList access 
    private: 
     Node* v;     // pointer to the node 
     Iterator(Node* u);   // create from node 
    }; 
    public: 
    NodeList();     // default constructor 
    int size() const;    // list size 
    bool empty() const;    // is the list empty? 
    Iterator begin() const;   // beginning position 
    Iterator end() const;   // (just beyond) last position 
    void insertFront(const Elem& e);  // insert at front 
    void insertBack(const Elem& e);  // insert at rear 
    void insert(const Iterator& p, const Elem& e); // insert e before p 
    void eraseFront();    // remove first 
    void eraseBack();    // remove last 
    void erase(const Iterator& p);  // remove p 
    private:     // data members 
    int  n;     // number of items 
    Node* header;    // head-of-list sentinel 
    Node* trailer;    // tail-of-list sentinel 
    }; 

我的代码不进行任何检查,以确定是否一个给定的位置(迭代器对象)实际上是一个特定的成员名单。例如,如果p是列表S中的一个位置,并且我将T.insert(p,e)调用到另一个列表T上,那么我实际上是在p之前将该元素添加到S中。我如何更改我的NodeList实现来禁止这种滥用?

回答

1

这将意味着一点内存开销,但是如果您将每个列表的头部存储在所有节点中,您可以检查头是否相同,那么它可能是相同的列表。

或者,如果您更喜欢cpu开销超过内存开销,请循环访问prev-links以查找这两个列表的头并按上述方式进行比较。

所以这取决于你喜欢哪种开销。