C++ 检查迭代器在哪个对象中的位置

C++ 检查迭代器在哪个对象中的位置,c++,C++,我有以下列表类: 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;

我有以下列表类:

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添加元素。如何更改节点列表实现以禁止这种误用?

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

或者,如果您更喜欢cpu开销而不是内存开销,则可以通过上一个链接找到两个列表的标题,并如上所述进行比较

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