确定某个职位是否是特定名单的成员

时间:2013-05-02 03:48:45

标签: c++

我有以下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上调用T.insert(p,e),那么我实际上是在p之前将元素添加到S.如何更改我的NodeList实现以禁止这种滥用?

1 个答案:

答案 0 :(得分:2)

让Iterator存储指向拥有它的NodeList的指针。

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
  NodeList* plist;
  Iterator(Node* u,NodeList* p);            // create from node

};

当您创建Iterator路径时,将其作为NodeList。然后在你的insert方法中,检查你的Iterator.plist == this