-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimple Iterator Implementation.cpp
More file actions
81 lines (66 loc) · 1.5 KB
/
Simple Iterator Implementation.cpp
File metadata and controls
81 lines (66 loc) · 1.5 KB
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
#include <iostream>
// Simple array container with iterator
template<typename T>
class Array {
private:
T* array;
int size;
public:
// Basic iterator class
class Iterator {
private:
T* ptr; // Pointer to current element
public:
// Constructor
Iterator(T* p = 0) : ptr(p) {}
// Dereference operator - get value
T& operator*() {
return *ptr;
}
// Increment operator (prefix)
Iterator& operator++() {
ptr++;
return *this;
}
// Comparison operators
bool operator!=(const Iterator& other) {
return ptr != other.ptr;
}
bool operator==(const Iterator& other) {
return ptr == other.ptr;
}
};
// Constructor
Array(int s = 10) : size(s) {
array = new T[size];
}
// Destructor
~Array() {
delete[] array;
}
// Get element at index
T& operator[](int index) {
return array[index];
}
// Iterator methods
Iterator begin() {
return Iterator(array);
}
Iterator end() {
return Iterator(array + size);
}
};
int main() {
Array<int> arr(5);
// Fill array with values
for (int i = 0; i < 5; i++) {
arr[i] = i * 10;
}
// Use iterator to print values
Array<int>::Iterator it;
for (it = arr.begin(); it != arr.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}