iterator class for list and vector

Hi,

I've written the source code vector and list.
I would like to write the iterator class for these classes

1
2
3
4
5
template <class T  class  Itor{ // common interface (abstract class)
public:
virtual T * first() = 0 ; // pointer to first element
virtual T * next() = 0 ; // pointer to next element
};

How do I write this class
How I write the iterator class for list and vector?

list and vector


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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
template<class T>
class List{
public:
	struct node{
	T  val;
	node *pnext;
	node *prev;
	node()
	{	
		pnext = 0;
		prev = 0;
	}
    };
   
	node *phead;
	node *ptail;
	size_t count;
public:
    List<T>()
    { 
       phead = 0;
	   ptail = 0;
	   count = 0;

    }

    node *push_front(T val)
	{
		node *pnewnode = new node;
		pnewnode->val  = val;
		pnewnode->pnext = phead;
		phead = pnewnode;

		if (ptail == 0)
			ptail =  pnewnode;

		count++;

		return pnewnode;

	}
    node *push_back(T val)
	{
		node *pnewnode = new node;
		pnewnode->val = val;
		pnewnode->pnext = 0;

		if (phead != 0)
			ptail->pnext = pnewnode;
		else
			phead = pnewnode;
		ptail = pnewnode;

		count++; 
        return pnewnode;
	}

    node *Insert(node *pNode, T val)
	{
		node *pnewnode = new node;
		pnewnode->val = val;

		pnewnode->pnext = pNode->pnext;
		pNode->pnext = pnewnode;
		pnewnode->prev = pNode;
		pnewnode->pnext->prev = pnewnode;

		if (ptail == pNode)
			ptail = pnewnode;
		count++;
		return pnewnode;
	}

	node *InsertNodeIndex(size_t index, T val)
	{
		node *pnode;


		if (index == 0) {
			return AddNodeHead(val);
		}
	
		
		pnode = phead;
		for (int i  = 0; i < index -1; ++i) 
			pnode = pnode->pnext;

		return Insert(pnode, val);

	}

	void Delete(node *pNode)
	{
		node *ptemp;
		ptemp = pNode->pnext;

		if (ptemp == ptail)
			ptail = pNode;
		pNode->pnext = ptemp->pnext;
		--count;
		delete ptemp;

	}


	bool DeleteNodeIndex(size_t index)
	{
		node *pnode;
		node *ptemp;

		if (index >= count){
			return false;

		if (index == 0)
			ptemp = phead;
		if (count == 1)
			ptail = 0;
		phead = ptemp->pnext;
		delete ptemp;
		--count;
		return true;
		}

		pnode = phead;
		for (int i= 0; i < index -1; ++i)
			pnode = pnode->pnext;
		Delete(pnode);

		return true;

	}

     void print()
	{
		node *p = phead;
		if (p == 0)
			cout << "Empty\n" << endl;
		int n = count;
		while(n--) {
			cout << p->val << endl;
		p = p->pnext;
		}	
	}};



thanks in advance.
Topic archived. No new replies allowed.