-
Notifications
You must be signed in to change notification settings - Fork 0
/
Iterator.cpp
127 lines (99 loc) · 2.21 KB
/
Iterator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class Container;
template <typename T>
class Iterator
{
public:
virtual T& first()=0;
virtual T& next()=0;
virtual bool end()=0;
virtual T& currentItem()=0;
virtual void setContainer(Container<T>* c)=0;
};
template <typename T>
class Container
{
public:
virtual Iterator<T>* createIterator()=0;
};
template <typename T>
class MyList;
template <typename T>
class ConcreteIterator : public Iterator<T>
{
public:
void setContainer(Container<T>* c){
this->con = c;
}
T& first(){
return (*(MyList<T>*)con)[0];
}
T& next(){
ret = nullptr;
if(++idx < ((MyList<T>*)con)->size()){
ret = &(*(MyList<T>*)con)[idx];
}
return *ret;
}
T& currentItem(){
if(ret) return *ret;
if(idx < ((MyList<T>*)con)->size()){
ret = &(*((MyList<T>*)con))[idx];
}
return *ret;
}
bool end(){
return idx >= ((MyList<T>*)con)->size() ? true : false;
}
private:
T* ret = nullptr;
int idx = 0;
Container<T>* con;
};
template <typename T>
class MyList : public Container<T>
{
public:
Iterator<T>* createIterator(){
Iterator<T>* ret = new ConcreteIterator<T>();
ret->setContainer(this);
return ret;
}
T& operator[](T t){
return l[t];
}
int size(){
return l.size();
}
void push_back(T t){
l.push_back(t);
}
private:
vector<T> l;
};
int main(){
MyList<int> ml = MyList<int>();
ml.push_back(1);
ml.push_back(2);
ml.push_back(3);
ml.push_back(4);
ml.push_back(5);
Iterator<int>* it = ml.createIterator();
int ele = it->first();
cout << ele << endl;
int& curEle = it->currentItem();
cout << curEle << endl;
curEle = 10;
int testEle = it->first();
cout << testEle << endl;
int nextEle = it->next();
cout << nextEle << endl;
ml[2] = 11;
int test2Ele = it->next();
cout << test2Ele << endl;
delete it;
return 0;
}