iterators.cpp 1.53 KB
Newer Older
Šmelko Adam Mgr.'s avatar
Šmelko Adam Mgr. committed
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
#include <vector>
#include <string>
#include <iostream>

struct person
{
    std::string name;
    int age;
};

class person_catalog
{
    std::vector<person> persons_;
public:
    person_catalog(std::vector<person> persons)
        : persons_(std::move(persons)) {}


    struct iterator
    {
        person_catalog& owner;
        int current_index;
        
        iterator(person_catalog& owner, int starting_index)
            : owner(owner), current_index(starting_index) {}

        person& operator*() 
        {
            return owner.persons_[current_index];
        }

        person* operator->()
        {
            return &owner.persons_[current_index];
        }

        bool operator!=(const iterator& oth) const
        {
            return &owner != &oth.owner || current_index != oth.current_index;
        }

        iterator& operator++()
        {
            current_index++;
            return *this;
        }
    };

    iterator begin()
    {
        return iterator(*this, 0);
    }

    iterator end()
    {
        return iterator(*this, persons_.size());
    }
};

int main()
{
    std::vector<person> persons;
    persons.push_back(person{"Adam", 24});
    persons.push_back(person{"Eva", 18});
    persons.push_back(person{"Michal", 13});

    person_catalog catalog(persons);

    for (auto it = catalog.begin(); it != catalog.end(); ++it)
    {
        std::cout << it->name << " ";
    }

    std::cout << std::endl;

    for (auto person : catalog)
        std::cout << person.name << " ";

    std::cout << std::endl;
}