example4_custom_implementation.cpp

 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
#include <iostream>
#include <iterator>

class Fibonacci {
private:
    int current;
    int next;

public:
    class iterator {
    private:
        int current;
        int next;
    public:
        using iterator_category = std::input_iterator_tag;
        using value_type = int;
        using difference_type = std::ptrdiff_t;
        using pointer = const int*;
        using reference = const int&;

        iterator(int current = 0, int next = 1) : current(current), next(next) {}

        int operator*() const { return current; }
        iterator& operator++() {
            int temp = current;
            current = next;
            next = temp + next;
            return *this;
        }
        iterator operator++(int) {
            iterator temp = *this;
            ++(*this);
            return temp;
        }
        bool operator==(const iterator& other) const { return current == other.current; }
        bool operator!=(const iterator& other) const { return !(*this == other); }
    };

    Fibonacci() : current(0), next(1) {}
    iterator begin() { return iterator(); }
    iterator end() { return iterator(89); } // Arbitrary end point
};

int main() {
    Fibonacci fib;
    std::cout << "First 10 Fibonacci numbers: ";
    int count = 0;
    for (auto i : fib) {
        if (count++ == 10) break;
        std::cout << i << " ";
    }
    std::cout << std::endl;

    return 0;
}
Back to iteratior