[英]Implement iterator of a circular list
我正在尝试使用迭代器的嵌套 class 实现循环列表的 class,我这样写:
template <class T>
class CircularList {
struct Item {
T data;
Item* next;
};
Item* head;
int size;
public:
CircularList() {
head = new Item();
head->next = head;
}
int sizeList() { return size; }
void push(T data) {
Item* i = new Item();
i->data = data;
i->next = head->next;
head->next = i;
size++;
}
class CircularListIterator {
Item* p;
CircularListIterator() {
p = head->next;
}
bool hasNext() {
if(p->next != head) {
return true;
}
return false;
}
T next() {
T data_temp = p->data;
p = p->next;
return data_temp;
}
};
CircularListIterator* iterator() {
return new CircularListIterator();
}
};
int main() {
CircularList<string>* letters = new CircularList<string>;
letters->push("d");
letters->push("c");
letters->push("b");
letters->push("a");
Iterator<string>* it= new Iterator<string>;
it = letters->iterator();
while (it->hasNext()) {
cout<< it->next() << "," << endl;
}
return 0;
}
但是当我尝试在主 function 中创建迭代器时,迭代器不起作用,它说它没有在 scope 中声明并且没有它的成员。
假设“在主类中”是指在main
function中,问题很简单:您正在尝试构造::Iterator<string>
,但在全局命名空间(或其他任何地方,在此代码示例)称为Iterator
! 您可以尝试构造一个CircularList<string>::CircularListIterator
- 这至少是一个存在的 class - 但它不起作用,因为迭代器需要与CircularList
object 相关联才能访问head
等成员变量。
正确的做法是将iterator
function(返回CircularListIterator*
的那个)从CircularListIterator
class 中提升到CircularList
ZA2F2ED4F8EBC2CBB64C21A29DC4 中。 然后,在您的main
function 中,您可以调用letters->iterator()
,它会为letters
object 返回一个CircularListIterator*
。
现在, CircularListIterator
不会从任何其他迭代器类继承 - 既不是(您输入的代码中不存在的Iterator
it
也不是 C++ std::iterator
或其任何变体) - 所以你不能将它分配给it
,甚至可能编译引用Iterator
的代码。 要使CircularListIterator
成为std::iterator
的子类,您需要使用适当的类别扩展std::iterator<Category, T>
。 有关std::iterator
class 模板的更多信息,包括实现它的示例,请参阅https://www.cplusplus.com/reference/iterator/iterator/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.