-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_circular_container_iterator.h
90 lines (76 loc) · 1.82 KB
/
my_circular_container_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
#ifndef __MY_CIRCULAR_CONTAINER_ITERATOR_H__
#define __MY_CIRCULAR_CONTAINER_ITERATOR_H__
/* NOTE! When the container size is 0, the behavior is not guranteed.
* It may run into infinite loop.
*/
template <class Container, class Iterator>
class MyCircularContainerIterator: public Iterator{
private:
const Container *c;
public:
MyCircularContainerIterator(const Container &_c, const Iterator _it)
: Iterator(_it), c(&_c)
{
}
MyCircularContainerIterator &operator=(const MyCircularContainerIterator &cit)
{
if (this == &cit) { // check for self-assignment
return *this;
}
Iterator &tmp(*this);
tmp = Iterator(cit);
this->c = cit.c;
return *this;
}
MyCircularContainerIterator &operator+=(int delta)
{
Iterator &tmp(*this);
tmp += delta;
while (tmp < c->cbegin()) {
tmp += c->size();
}
while (tmp >= c->cend()) {
tmp -= c->size();
}
return *this;
}
MyCircularContainerIterator &operator-=(int delta)
{
return operator+=(-delta);
}
MyCircularContainerIterator &operator++() // ++i
{
return operator+=(1);
}
const MyCircularContainerIterator operator++(int) // i++
{
MyCircularContainerIterator tmp(*this);
operator++();
return tmp;
}
MyCircularContainerIterator &operator--() // --i
{
return operator-=(1);
}
const MyCircularContainerIterator operator--(int) // i--
{
MyCircularContainerIterator tmp(*this);
operator--();
return tmp;
}
const MyCircularContainerIterator operator+(int delta) const
{
return MyCircularContainerIterator(*this) += delta;
}
const MyCircularContainerIterator operator-(int delta) const
{
return operator+(-delta);
}
// The index returned only works for Container that supports random access
const typename Container::size_type iterator2index(void) const
{
const Iterator &tmp(*this);
return tmp - c->cbegin();
}
};
#endif