如何实现CyclicList的迭代器?

时间:2016-09-25 18:51:53

标签: c++ iterator

具有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++行: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);
  }

1 个答案:

答案 0 :(得分:0)

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

删除时,

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

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