[cpp]
- template <class T>
- class vector {
- private:
- T* pbegin;
- int n; //当前大小
- public:
- vector() {
- pbegin = new T[100]; //暂时先固定大小
- n = 0;
- }
- T* begin() {
- return pbegin;
- }
- void insert(T d){
- pbegin[n++] = d;
- }
- typedef T* iterator; //vector的迭代器就是基础指针类型
- };
[cpp]
- //测试vector
- vector<int> a;
- a.insert(1);
- a.insert(2);
- vector<int>::iterator itra;
- itra = a.begin();
- printf("%d/n", *itra);
- itra++;
- printf("%d/n", *itra);
- itra--; //基础指针类型都支持++,--,+,-等操作符
- printf("%d/n", *itra);
[cpp]
- template <class T>
- class List{
- private:
- struct Node{ //链表的节点
- T data;
- Node* next;
- };
- Node* pbegin; //表头
- class List_iterator{ //链表的迭代器
- Node* cur; //当前指向
- public:
- void operator = (Node* ptr) {
- cur = ptr;
- }
- void operator ++ () {
- cur = cur->next;
- }
- // ...还可以重载-- + -等操作符
- T operator * (){
- return cur->data;
- }
- };
- public :
- List() {
- pbegin=NULL;
- }
- Node* begin() {
- return pbegin;
- }
- void insert(T d) {
- Node* p=pbegin;
- while(p && p->next) p=p->next;
- Node* t = new Node;
- t->data = d;
- t->next = NULL;
- if(pbegin==NULL)
- pbegin = t;
- else
- p->next = t;
- }
- typedef List_iterator iterator; //List的迭代器是一个类
- };
[cpp]
- /测试List
- List<int> b;
- b.insert(1);
- b.insert(2);
- List<int>::iterator itrb;
- itrb = b.begin();
- printf("%d/n", *itrb);
- itrb++; // 该迭代器只支持++
- printf("%d/n", *itrb);