-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjava_iterator.hpp
executable file
·128 lines (99 loc) · 2.61 KB
/
java_iterator.hpp
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
#ifndef ITERATOR_HPP_08761A81_0F2B_4C82_B00D_DA36B94245A6
#define ITERATOR_HPP_08761A81_0F2B_4C82_B00D_DA36B94245A6
// Author: David Charles Haley
// (c) 2006 David Charles Haley
// Java-style iterator
namespace JavaIteratorPrivate
{
template<typename ValueType>
class IteratorImplBase
{
public:
virtual ~IteratorImplBase() { /* empty */ }
virtual bool hasNext() const = 0;
virtual ValueType next() = 0;
virtual size_t size() const = 0;
virtual IteratorImplBase<ValueType> * copy() const = 0;
};
template<typename ContainerType>
class IteratorImpl : public IteratorImplBase<typename ContainerType::value_type>
{
public:
IteratorImpl(const ContainerType & con)
: container_(con)
{
it_ = container_.begin();
}
~IteratorImpl() { /* empty */ }
bool hasNext() const
{
return it_ != container_.end();
}
typename ContainerType::value_type next()
{
typename ContainerType::value_type val = *it_;
it_++;
return val;
}
size_t size() const
{
typename ContainerType::const_iterator it2 = it_;
size_t count = 0;
while ( it2++ != container_.end() )
count++;
return count;
}
IteratorImplBase<typename ContainerType::value_type> * copy() const
{
return new IteratorImpl<ContainerType>(container_);
}
private:
const ContainerType & container_;
typename ContainerType::const_iterator it_;
};
} // namespace JavaIteratorPrivate
template<typename ValueType>
class Iterator
{
public:
Iterator(JavaIteratorPrivate::IteratorImplBase<ValueType> * impl = NULL)
{
impl_ = impl;
}
~Iterator()
{
delete impl_;
}
bool hasNext() const
{
return impl_->hasNext();
}
ValueType next()
{
return impl_->next();
}
/** \brief Return how many elements are left in this iterator.
*
* \return How many elements are yet to be iterated over.
*/
size_t size() const
{
return impl_->size();
}
Iterator<ValueType> & operator = (const Iterator<ValueType> & rhs)
{
// Do we have an implementation? If so, delete it
if ( impl_ ) delete impl_;
// Make a copy of the implementation
impl_ = rhs.impl_->copy();
return *this;
}
protected:
JavaIteratorPrivate::IteratorImplBase<ValueType> * impl_;
};
template<typename ContainerType>
inline Iterator<typename ContainerType::value_type> MakeIterator(const ContainerType & container)
{
return Iterator<typename ContainerType::value_type>( new JavaIteratorPrivate::IteratorImpl<ContainerType>(container) );
}
#endif // include guard