如何实现列表:<T>:迭代器?

How to implement list<T>::iterator?

本文关键字:何实现 gt 迭代器 lt 实现 列表      更新时间:2023-10-16

我知道如何实现模板类。
但是,我不明白以下list<int>::iterator是如何在内部实现的。我应该创建一个命名空间吗?
(基本上我想在自定义实现中使用相同的 STL 语法。

list<int> l;
list<int>::iterator it = l.begin();

简而言之,在没有任何 STL 库的情况下让代码工作的最简单方法是什么?

下面是自定义列表实现的一个片段: (为了提高可读性,我省略了大多数方法。

template <typename T>
struct list {
struct listNode {
listNode() : item(0), next(0) {}
listNode(T x) : item(x), next(0) {}
T item;
listNode* next;
};
list() : head(0),tail(0) {}     
listNode* head;
listNode* tail;
};

可以在容器类型中实现迭代器类型,以便它包含有关它正在迭代的容器的任何信息。

template<class T>
class SomeContainer {
public:
class Iterator {
// You can use SomeContainer and T in here.  
};
};