具有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
(以及Begin
和End
),以便以下两个代码段都正常工作
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; }
Iterator
,Begin
和End
实施:
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);
}
答案 0 :(得分:0)
对于迭代器,在迭代时修改容器通常不是一个好主意。
删除时, it
仍在first
。执行++it
时,it.p->next
未定义(行为)。我的计算机it.p->next
与first
不同,因此it.done
未设置为true
。下一个delete
删除一个未定义的指针,所以错误。
除此之外,我不确定您是否真的需要为end
单元格分配。您的迭代器主要使用其字段done
。