繁体   English   中英

如何实现CyclicList的迭代器?

[英]How to implement an iterator to a CyclicList?

具有CyclicList的以下实现:

struct LItem {
  LItem* next;
  LItem* prev;
};

class CyclicList {
public:
  LItem* Remove(LItem* item) {
    if(root == item) {
      root = root->prev;
      if(root == item) {
        root = nullptr;
        item->next = item->prev = nullptr;
        return item;
      }
    }
    item->next->prev = item->prev;
    item->prev->next = item->next;
    item->next = item->prev = nullptr;
    return item;
  }
  LItem* Insert(LItem* item) {
    if(root) {
      item->next = root->next;
      item->prev = root;
      item->next->prev = item;
      item->prev->next = item;
    } else
      item->next = item->prev = item;
    root = item;
    return item;
  }

public:
  class Iterator {
  public:
    void operator++();
    LItem* operator*();
    bool operator!=(const Iterator&);
  };
  Iterator Begin();
  Iterator End();

private:
  LItem* root;
};

是否可以实现iterator (与BeginEnd一起),以便以下两个片段都正常工作

size_t count = 0;
for( auto it=list.Begin() ; it != list.End() ; ++it )
    ++count;
for( auto it=list.Begin() ; it != list.End() ; ++it )
    delete list.Remove(*it);

我到目前为止的尝试如下:

将此添加到CyclicList

LItem* end;
CyclicList() : root(nullptr), end(new LItem) {}
~CyclicList() { delete end; }

IteratorBeginEnd实现:

  class Iterator {
    LItem* beg;
    LItem* p;
    bool done;

  public:
    void operator++() {
      p = p->next;
      if(p == beg) done = true;
    }
    LItem* operator*() { return p; }
    bool operator!=(const Iterator& rhs) { return !(rhs.p == p) || done != rhs.done; }
    Iterator(LItem* p, bool done) : beg(p), p(p), done(done) {}
  };

  Iterator Begin() { return Iterator(root, false); };
  Iterator End() { return Iterator(root, true); };

它允许我这样做:

{
  CyclicList list;
  LItem* first = new LItem();
  LItem* second = new LItem();
  list.Insert(first);
  list.Insert(second);

  size_t count = 0;
  for(auto it = list.Begin(); it != list.End(); ++it) ++count;

  assert(count == 2);

  delete first;
  delete second;
}
{
  CyclicList list;
  LItem* first = new LItem();
  LItem* second = new LItem();
  list.Insert(first);
  list.Insert(second);
  delete list.Remove(*list.Begin());
  delete list.Remove(*list.Begin());
}

但是在释放之后给堆使用(指向operator++ line: p = p->next; ):

  CyclicList list;
  LItem* first = new LItem();
  list.Insert(first);
  for(auto it = list.Begin(); it != list.End(); ++it) {
    delete list.Remove(*it);
  }

对于迭代器,在迭代时修改容器通常不是一个好主意。

当你删除它时it仍然是first 执行++itit.p->next是未定义的(行为)。 在我的机器上it.p->nextfirst不同,因此it.done未设置为true 下一次delete删除一个未定义的指针,所以错误。

除此之外,我不确定您是否真的需要为end单元格分配。 你的迭代器主要用于done它的字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM