-
Notifications
You must be signed in to change notification settings - Fork 0
/
Custom_Iterator.h
112 lines (91 loc) · 1.97 KB
/
Custom_Iterator.h
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
#include <iostream>
using std::cout;
using std::endl;
namespace custom_iterator {
template< typename T > class vector {
public:
vector() {
size_ = 0;
capacity = CAPACITY;
data = new T[ capacity ];
}
~vector() {
delete [] data;
data = NULL;
size_ = 0;
}
/* iterator class */
class iterator {
public:
iterator() {}
iterator( T *ptr ) {
current = ptr;
}
/* overload != operator */
bool operator!=( const iterator &rhs ) {
return this->current != rhs.current;
}
/* overload prefix ++ operator */
iterator& operator++() {
++current;
return *this;
}
/* overload prefix -- operator */
iterator& operator--() {
--current;
return *this;
}
/* overload * (de-reference) operator */
T& operator*() {
return *current;
}
private:
T *current;
}; /* iterator class ends here */
iterator begin() const {
return iterator( data );
}
iterator end() const {
return iterator( data + size_ );
}
/* reverse begin */
iterator rbegin() const {
return iterator( data + size_ - 1 );
}
/* reverse end */
iterator rend() const {
return iterator( data - 1 );
}
int size() {
return size_;
}
void push_back( const T &value ) {
if( size_ == capacity )
expand();
data[ size_ ] = value;
size_++;
}
const T& operator[]( int pos ) const {
return data[ pos ];
}
T& operator[]( int pos ) {
return data[ pos ];
}
private:
void expand();
const int CAPACITY = 16;
unsigned int size_;
unsigned int capacity;
T *data;
};
template<typename T>
void vector<T>::expand() {
capacity += CAPACITY;
T *newData = new T[ capacity ];
for( int i = 0; i < size_; i++ ) {
newData[ i ] = data[ i ];
}
delete [] data;
data = newData;
}
} // namespace custom_iterator ends