foreach.cpp
772 Bytes
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
#include <stddef.h>
#include <iostream>
class Iterator;
class Collection
{
static const size_t size = 10;
int data[size];
using iterator = Iterator;
friend class Iterator;
public:
Iterator begin();
Iterator end();
};
class Iterator
{
int i;
Collection* c;
public:
Iterator(int ii, Collection* cc) : i(ii), c(cc){};
int& operator *()
{
return c->data[i];
}
Iterator& operator++()
{
++i;
return *this;
}
bool operator!=(const Iterator& o)
{
return i != o.i;
}
};
Iterator Collection::begin()
{
return Iterator(0,this);
}
Iterator Collection::end()
{
return Iterator(Collection::size-1,this);
}
int main()
{
Collection c;
int a = 3;
for(auto& i: c)
i = a++;
for(auto i: c)
std::cout << i << std::endl;
}