-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterator_with_operators.cpp
More file actions
119 lines (98 loc) · 2.69 KB
/
iterator_with_operators.cpp
File metadata and controls
119 lines (98 loc) · 2.69 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
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
/**
* \file
* \brief
*
* \todo
*/
/*
Intent:
- Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
- The C++ and Java standard library abstraction that makes it possible to decouple collection classes and algorithms.
- Promote to �full object status� the traversal of a collection.
- Polymorphic traversal
Problem:
Need to �abstract� the traversal of wildly different data structures so that algorithms can be defined that are capable of interfacing with each transparently.
*/
/*
Design an �iterator� class for the �container� class
Add a createIterator() member to the container class
Clients ask the container object to create an iterator object
Clients use the first(), isDone(), next(), and currentItem() protocol
*/
#include <iostream>
//---------------------------------------------------------------------------
class StackIter;
class Stack {
public:
friend class StackIter;
Stack() {
sp = - 1;
}
void push(int in) {
items[++sp] = in;
}
int pop() {
return items[sp--];
}
bool isEmpty() {
return (sp == - 1);
}
private:
int items[10];
int sp;
};
//---------------------------------------------------------------------------
class StackIter {
public:
StackIter(const Stack &s): stk(s) {
index = 0;
}
void operator++(){
index++;
}
bool operator()() {
return index != stk.sp + 1;
}
int operator *() {
return stk.items[index];
}
private:
const Stack &stk;
int index;
};
//---------------------------------------------------------------------------
bool
operator == (const Stack &l, const Stack &r) {
StackIter itl(l), itr(r);
for (; itl(); ++itl, ++itr) {
if (*itl != *itr) {
break;
}
}
return !itl() && !itr();
}
//---------------------------------------------------------------------------
int main()
{
Stack s1;
for (int i = 1; i < 5; i++) {
s1.push(i);
}
Stack s2(s1), s3(s1), s4(s1), s5(s1);
s3.pop();
s5.pop();
s4.push(2);
s5.push(9);
std::cout << "1 == 2 is " << (s1 == s2) << std::endl;
std::cout << "1 == 3 is " << (s1 == s3) << std::endl;
std::cout << "1 == 4 is " << (s1 == s4) << std::endl;
std::cout << "1 == 5 is " << (s1 == s5) << std::endl;
}
//---------------------------------------------------------------------------
/*
Output:
1 == 2 is 1
1 == 3 is 0
1 == 4 is 0
1 == 5 is 0
*/